Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Wednesday, 13 January 2016

Register as a facebook developer phone number verification problem

Facebook make sure developers to register as a facebook developer before creating a facebook login project.

Register as a Facebook Developer

You can register yourself as a facebook developer by two ways.
1- You need to verify your account to complete your registration with Phone Number.
2- You can also verify your account by adding a credit card
        
If you try for the first time to create an application for Facebook, most probably, right after you press the “+Set Up New App” button or the “Create one” link, you will get an error message like this:
Your account must be verified before you can take this action. Please verify your account by adding your Mobile phone or Credit/debit card.
If you press Mobile phone, you will are at My Account->Mobile-> Activate a Phone. The only available option is “Register for Facebook Text Messages”. And this is where Facebook starts to fail developers. You get a window to state your Country and Mobile Carrier, but SURPRISE!…There are just a few countries there (Romania not included), so you cannot get your Confirmation code, you cannot get to the next step.
This is when I started to wonder if Facebook does ever test its code. Probably not.
After some hours of research, this is my solution in 3 baby-steps:
1. Go to this address: http://www.facebook.com/confirmphone.php/ and input your phone number
2. You will receive an SMS with the confirmation code and a link
3. The confirmation code will probably generate an error (“Sorry, that was an invalid confirmation code”) – this is hilarious isn’t it? – but if you follow the link on your mobile, the phone will be activated.
Most helpful resources should have been on Facebook.com, but they were found on: http://jesperastrom.com/facebook/
Update:
It seems that this error is affecting the Facebook developer community a lot.
If your account still doesn’t work, add your phone number at: https://www.facebook.com/update_security_info.php
Upon receiving the same error, address Facebook with a bug ticket at:
http://bugs.developers.facebook.net/

Tuesday, 4 February 2014

JSON Parsing in Android

JSON Stands for JAVA Script Object Notation. It is light weight structured, easy to parse and very easy to human readable. JSON is independent data exchange formate and best alternate for  XML.

In this tutorial we are going to learn how to put values in JSON in Android, and how to parse a JSON data set in Android.

Android provides four differnet classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.

Difference between [ and { (Square and Curly brackets).

Generally all JSON data set node starts with a square or curly brackets
when a json starts with square brackets its an Array and when a node starts with a curly bracket its an object. to manipulate an JSON array use JSONArray obj. and manipulating JSON object use JSONObject object.
in short
If your JSON node starts with [, then we should use getJSONArray() method. Same as if the node starts with {, then we should use getJSONObject() method.

package com.ashfaq.jsonparsing;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class XMLDemo extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
               
        putValueJson();  // values putting in json
        jsonParsing();   // Json parsing        
       
    }


    private void putValueJson() {
        // TODO Auto-generated method stub
        JSONObject obj = new JSONObject();
        try {
            obj.put("name", "Ashfaq");
            obj.put("PG", true);
            obj.put("num", new Integer(100));
            obj.put("balance", new Double(1000.15));
           
            Log.d("Json : ",""+ obj);
           
           
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   
    private void jsonParsing() {
       
        String s = "{\"FirstObject\":{\"attr1\":\"one value\" ,\"attr2\":\"two value\","
                +"\"sub\": { \"sub1\":[ {\"sub1_attr\":\"sub1_attr_value\" },{\"sub1_attr\":\"sub2_attr_value\" }]}}}";
       
        try {
            JSONObject jobj = new JSONObject(s);
            JSONObject nobj = jobj.getJSONObject("FirstObject");
            String atr1 = nobj.getString("attr1");
            String atr2 = nobj.getString("attr2");
           
            Log.d("json value  atr1 ", atr1 +" atr2 "+atr2);
           
            JSONObject sobj = nobj.getJSONObject("sub");
            JSONArray bary = sobj.getJSONArray("sub1");
            String s2 = "" ;
            for(int i=0;i<bary.length();i++){
            //     s2 = "\n"+bary.getJSONObject(i).getString("sub1_attr").toString();
               
                 JSONObject jsno = bary.getJSONObject(i);
                 String astr = jsno.getString("sub1_attr");
                // String astr1 = jsno.getString("sub1_attr");
                    Log.d("json value ",astr );
            }
           
   
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
    }

}
 


Friday, 31 January 2014

Android Basic SQLite Tutorial for beginers

If you are just a  bigenner of Android app developer, after some basic apps you'll need to store your data in database like user name and password, high score of the game or much more. Android provides a simple and lite as name SQLite database to manage the Database.

What is SQLite

SQLite is a relational database (RDBMS). what makes SQLite unique is that it is considered as embedded solution. Most database management system such as Oracle, MySQL, and SQL Server are standalone server processes that run independently.

SQLite is actually a library that is linked into applications. All database operations are handled within the application through calls and functions contained in the SQLite library.

I am going to show you how to insert,update and delete data in SQLite.

create a new Project in your eclipse called UserDetail

Some Snapes of App
Home page screen shot


New Form Screen shot
// MainActivity.java

package com.example.userdetail;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
   
    Button newForm,toServer,editmode,delete_db;
    DataBaseHelper dbHelper;
    SQLiteDatabase mDB;
    Cursor mcur;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        dbHelper = new DataBaseHelper(this);
       
        newForm = (Button)findViewById(R.id.nform);
        toServer = (Button)findViewById(R.id.sendtoserver);
        editmode = (Button)findViewById(R.id.edit);
        delete_db = (Button)findViewById(R.id.delete_db);
       
        delete_db.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
                try {
                    // Delete DataBase
                    mDB = dbHelper.getWritableDatabase();
                    mDB.execSQL("DROP TABLE "+DataBaseHelper.USER_TABLE);
                    dbHelper.onCreate(mDB);
                   
                } catch (Exception e) {
                    e.printStackTrace();
                }
               
            }
        });
       
        editmode.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,DataList.class);
                startActivity(intent);
            }
        });
       
        newForm.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View arg0) {
                Intent form = new Intent(getApplicationContext(),NewForm.class);
                form.putExtra("update", false);
                startActivity(form);
               
            }
        });
       
        toServer.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
                          
                dbHelper = new DataBaseHelper(MainActivity.this);
                mDB = dbHelper.getReadableDatabase();
               
                String getData = "SELECT "+DataBaseHelper.NAME+","+DataBaseHelper.GENDER+","+DataBaseHelper.AGE+
                        " From "+DataBaseHelper.USER_TABLE;
                mcur = mDB.rawQuery(getData, null);
                int totalData = mcur.getCount();
                mcur.moveToFirst();
                for(int i=0;i<totalData;i++){
                   
                    String name = mcur.getString(0);
                    String gender = mcur.getString(1);
                    int age = mcur.getInt(2);
                   
                    try {
   // put your url here
                        URL url = new URL("http://www.exmple.com");
                        HttpURLConnection urlc = (HttpURLConnection)   url.openConnection();
                        urlc.setRequestProperty("Connection", "close");
                        urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
                                urlc.connect();
                        if (urlc.getResponseCode() == 200) {
                           
                            Log.d("Response", "==200");
                            Toast.makeText(MainActivity.this, "Successfull", Toast.LENGTH_LONG).show();
                           
                            // Delete DataBase
                            mDB = dbHelper.getWritableDatabase();
                            mDB.execSQL("DROP TABLE "+DataBaseHelper.USER_TABLE);
                            dbHelper.onCreate(mDB);
                        }
                    }  catch (IOException e) {
                        Toast.makeText(MainActivity.this, "Faild", Toast.LENGTH_LONG).show();
                        Log.d("Response", "!=200");
                        e.printStackTrace();
                    } 
                   
                    Log.d("DATA", "Name : "+name+", Gender : "+gender+", Age : "+age);
                    mcur.moveToNext();
                    mDB.close();
                }
               
            }
        });
    }

    @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);
        return true;
    }
   
}

 // NewForm.java   // class

package com.example.userdetail;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class NewForm extends Activity{
   
    EditText name,age;
    Button savetoDb;
    RadioGroup radioSexGroup;
    RadioButton radioSexButton;
    DataBaseHelper dbHelper;
    SQLiteDatabase mDB;
    boolean isUpdate;
    String id,uName,uAge,uGen;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form);
       
        name = (EditText)findViewById(R.id.ename);
        age = (EditText)findViewById(R.id.eage);
        radioSexGroup = (RadioGroup)findViewById(R.id.radiogender);
        savetoDb = (Button)findViewById(R.id.savetoSqlite);
       
        isUpdate = getIntent().getExtras().getBoolean("update");
       
        if(isUpdate){
            id = getIntent().getExtras().getString("id");
            uName = getIntent().getExtras().getString("name");
            uAge = getIntent().getExtras().getString("age");
        //    uGen = getIntent().getExtras().getString("gender");
           
            name.setText(uName);
            age.setText(uAge);
        //    radioSexButton.setText(uGen);
        }
       
        savetoDb.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
               
                dbHelper = new DataBaseHelper(NewForm.this);
                mDB = dbHelper.getWritableDatabase();
               
                int selectedId = radioSexGroup.getCheckedRadioButtonId();
                radioSexButton = (RadioButton)findViewById(selectedId);
               
                String uName = name.getText().toString();
                String uSex = radioSexButton.getText().toString();
                String uAge  = age.getText().toString();
                int intAge = Integer.parseInt(uAge);
               
                ContentValues cv = new ContentValues();
                cv.put(DataBaseHelper.NAME, uName);
                cv.put(DataBaseHelper.GENDER, uSex);
                cv.put(DataBaseHelper.AGE,intAge );
               
                if(isUpdate){
                    // update database with new data
                    mDB.update(DataBaseHelper.USER_TABLE, cv, DataBaseHelper.KEY_ID +"="+id, null);
                }else{
                    // insert new data into database 
                mDB.insert(DataBaseHelper.USER_TABLE, null, cv);
                }
               
                Toast.makeText(getApplicationContext(),"Name : "+uName+",Age : "+intAge+", Sex :" +radioSexButton.getText(), Toast.LENGTH_LONG).show();
                mDB.close();
                finish();
            }
        });
       
    }

}

// DataBaseHelper.java

package com.example.userdetail;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper{
   
    public static final int DB_VERSION = 1;
    public static final String DATABASE_NAME = "details.db";
    public static final String USER_TABLE = "user_detail";
    public static final String KEY_ID = "id";
    public static final String NAME = "name";
    public static final String GENDER = "gender";
    public static final String AGE = "age";
   

    public DataBaseHelper(Context ctx) {
        super(ctx, DATABASE_NAME, null, DB_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String TABLE = "CREATE TABLE "+USER_TABLE+"("+KEY_ID+" INTEGER PRIMARY KEY, "+NAME+" TEXT,"
                       +GENDER+" INTEGER,"+AGE+" INTEGER"+")";
        db.execSQL(TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+USER_TABLE);
        onCreate(db);
    }
   

}

 // DataList.java  

package com.example.userdetail;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class DataList extends Activity{
    ListView listv;
    DataBaseHelper dbHelper;
    SQLiteDatabase mDB;
    Cursor mCur;
    View v;
   
    private ArrayList<String> userId = new ArrayList<String>();
    private ArrayList<String> user_fName = new ArrayList<String>();
    private ArrayList<String> user_age = new ArrayList<String>();
    private ArrayList<String> user_gender = new ArrayList<String>();
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.displaylist);
        listv = (ListView)findViewById(R.id.list);
        v = (View)findViewById(R.id.view);
       
        v.setBackgroundColor(Color.BLUE);
   
        // edit datalist
        listv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView <?>args0,View args1,int args2,long args3){
                Intent i = new Intent(getApplicationContext(),NewForm.class);
                i.putExtra("id", userId.get(args2));
                i.putExtra("name", user_fName.get(args2));
                i.putExtra("age", user_age.get(args2));
                i.putExtra("gender", user_gender.get(args2));
                i.putExtra("update", true);
                startActivity(i);
            }
        });
       
        dbHelper = new DataBaseHelper(DataList.this);
       
        displayData();
       
    }
   
@SuppressWarnings("static-access")
private void displayData() {
    dbHelper = new DataBaseHelper(DataList.this);
        mDB = dbHelper.getWritableDatabase();
        String query = "SELECT "+"* "+"FROM "+DataBaseHelper.USER_TABLE;
        mCur = mDB.rawQuery(query, null);
    //    mCur = mDB.rawQuery("SELECT * FROM "+dbHelper.USER_TABLE,null );
        userId.clear();
        user_fName.clear();
        user_age.clear();
        user_gender.clear();
        if(mCur.moveToFirst()){
            do{
                userId.add(mCur.getString(mCur.getColumnIndex(dbHelper.KEY_ID)));
                user_fName.add(mCur.getString(mCur.getColumnIndex(dbHelper.NAME)));
                user_age.add(mCur.getString(mCur.getColumnIndex(dbHelper.AGE)));
                user_gender.add(mCur.getString(mCur.getColumnIndex(dbHelper.GENDER)));
            }while(mCur.moveToNext());
        }
        DisplayAdapter disadpt = new DisplayAdapter(DataList.this,userId, user_fName, user_age,user_gender);
        listv.setAdapter(disadpt);
        mCur.close();
    }
   
@Override
protected void onResume() {
   
    super.onResume();
    displayData();
}

}

// DisplayAdapter

package com.example.userdetail;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class DisplayAdapter extends BaseAdapter{
   
    private Context ctx;
    private ArrayList<String>id;
    private ArrayList<String>name;
    private ArrayList<String>age;
    private ArrayList<String>gender;
   
    public DisplayAdapter(Context c,ArrayList<String>id,ArrayList<String>name,ArrayList<String>age,ArrayList<String>gen){
        this.ctx = c;
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gen;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return id.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder;
        LayoutInflater layoutinflater;
        if(child == null){
            layoutinflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutinflater.inflate(R.layout.listcell, null);
            mHolder = new Holder();
            mHolder.txt_id = (TextView)child.findViewById(R.id.txt_id);
            mHolder.txt_name = (TextView)child.findViewById(R.id.txt_name);
            mHolder.txt_age = (TextView)child.findViewById(R.id.txt_age);
            mHolder.txt_gen = (TextView)child.findViewById(R.id.txt_gender);
            child.setTag(mHolder);
        }else{
            mHolder = (Holder)child.getTag();
        }
        mHolder.txt_id.setText(id.get(pos));
        mHolder.txt_name.setText(name.get(pos));
        mHolder.txt_age.setText(age.get(pos));
        mHolder.txt_gen.setText(gender.get(pos));
        return child;
    }
   
    public class Holder{
        TextView txt_id;
        TextView txt_name;
        TextView txt_age;
        TextView txt_gen;
    }

}

/Layout
// activity_main.xml

<LinearLayout 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:orientation="vertical"
    android:padding="10dip"
    android:gravity="center_vertical">

    <Button
        android:id="@+id/nform"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"      
        android:text="New Form" />
   
    <Button
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"     
        android:text="Edit" />
   
    <Button
        android:id="@+id/sendtoserver"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"     
        android:text="Send to Server" />
   
    <Button
        android:id="@+id/delete_db"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"     
        android:text="Delete DATA" />

</LinearLayout>

// form.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout 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:orientation="vertical">
       
    <EditText
        android:id="@+id/ename"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dip"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginBottom="25dip"
        android:hint="Enter Name"
        android:inputType="text">
        <requestFocus/>
    </EditText>
   
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginBottom="5dip"
        android:textSize="15dip"
        android:text="Gender:"/>
   
    <RadioGroup
        android:id="@+id/radiogender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dip"
        android:layout_marginLeft="20dip">
       
        <RadioButton
            android:id="@+id/male"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Male"
            android:checked="true"/>
       
        <RadioButton
            android:id="@+id/female"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="female"/>
       
    </RadioGroup>
   
    <EditText
        android:id="@+id/eage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint=" Age "
        android:inputType="number"
        android:layout_marginTop="20dip"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip">     
    </EditText>
   
    <Button android:id="@+id/savetoSqlite"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Save Data"
        android:layout_marginTop="20dip"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"/>
       
       
   </LinearLayout>

// displaylist.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout 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:orientation="vertical">
   
    <LinearLayout
   
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#F3CAE5"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="8dp" >
   
    <TextView
       
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="ID"
        android:textColor="#000" />

    <TextView
        android:text="Name"
        android:layout_width="55dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColor="#000" />

    <TextView
        android:text="Gender"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:textColor="#000" />

    <TextView
        android:text="Age"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:textColor="#000" />

</LinearLayout>

    <View android:id="@+id/view"
        android:layout_width="fill_parent"
        android:layout_height="2dip"  /> 

    <ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:divider="#8DB3E1"
        android:dividerHeight="1dp">
    </ListView>
         
   
</LinearLayout>

//listcell.xml

<LinearLayout 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:background="#F3CAE5"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="8dp" >
   
   
    <TextView
        android:id="@+id/txt_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="17dp"
        android:textColor="#000" />

    <TextView
        android:id="@+id/txt_name"
        android:layout_width="55dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
         android:textSize="17dp"
        android:textColor="#000" />

    <TextView
        android:id="@+id/txt_gender"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
         android:textSize="17dp"
        android:textColor="#000" />

    <TextView
        android:id="@+id/txt_age"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
         android:textSize="17dp"
        android:textColor="#000" />

</LinearLayout>

// UserDetailManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.userdetail"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/userTheme" >
        <activity
            android:name="com.example.userdetail.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=".NewForm"/>
        <activity
            android:name=".DataList"/>
    </application>

</manifest>


Thursday, 26 December 2013

Building Web Apps in WebView

If you want to deliver a web application (or just a web page) as a part of a client application, you can do it using WebView. The WebView class is an extension of Android's View class that allows you to display web pages as a part of your activity layout.It does not include any features of a fully developed web browser, such as navigation controls or an address bar. All that WebView does, by default, is show a web page.

Create your layout: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<WebView 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

within your Activity: MainActivity.java

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
    WebView webView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        webView = (WebView)findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);

// Handling page navigation
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("http://ashfaquedl.blogspot.in/");
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
    }
//  Navigating web page history
    @Override
    public void onBackPressed() {
        if (webView.copyBackForwardList().getCurrentIndex() > 0) {
            webView.goBack();
        }
        else {
            // Your exit alert code, or alternatively line below to finish
            super.onBackPressed(); // finishes activity
        }
    }

}
 Note: And most important thing don't forget to add below uses-permission in AndroidMenifest.xml.

<uses-permission android:name="android.permission.INTERNET"/>
now your app is rocking.
 

Tuesday, 19 November 2013

How to clear cache in Android Manually & Programmatically

What the android os does is when you exit an application it actually stores the apps cache on either your phones internal storage or on the sdcard; so what this does, is that when you load the application next time, it immediately loads the stored cache back into your active cache for the purpose of speeding up loading time. So in theory, stored cache is actually a good thing.
However, this is not always the case.
Its only really a beneficial feature for certain applications, like Google maps, where loading all those images normally takes a long time (relatively speaking of course.. its still really fast). An even better example would be your launcher app; your always loading the exact same homescreens everytime. But for other apps it actually is a bad thing and bogs your system down. Why? Because your taking over the fastest available memory on your device with stored data that might not be essential/relevant for what your doing the next time you load the application. A good example would be your web browser. The last time you ran it you were checking the news or watching youtube videos... but now your just doing a google search; you certainly don't need to load the cache from your last session. Get it? 

Clear Cache manually 
< Applications --> Manage Applications --> "My App" --> Clear Cache>> 
Clear cache programmatically

import java.io.File;

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

public class HelloWorld extends Activity {

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle *) {
      super.onCreate(*);
      setContentView(R.layout.main);
   }

   @Override
   protected void onStop(){
      super.onStop();
   }

   //Fires after the OnStop() state
   @Override
   protected void onDestroy() {
      super.onDestroy();
      try {
         trimCache(this);
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

   public static void trimCache(Context context) {
      try {
         File dir = context.getCacheDir();
         if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
         }
      } catch (Exception e) {
         // TODO: handle exception
      }
   }

   public static boolean deleteDir(File dir) {
      if (dir != null && dir.isDirectory()) {
         String[] children = dir.list();
         for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
               return false;
            }
         }
      }

      // The directory is now empty so delete it
      return dir.delete();
   }

}
  
 

Wednesday, 13 November 2013

How to save SMS to INBOX in Android Programmatically


There is below code

                ContentValues values = new ContentValues();
                values.put("address", "123456789");
                values.put("body", "foo bar");
                getContentResolver().insert(Uri.parse("content://sms/inbox"), values);

you can save SMS to Sent box also just require to few change.
Replace  ("content://sms/inbox") to ("content://sms/sent").



Below Android Permissions required

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