Thursday 17 December 2015

Display Progress Dialog without Text and Transparent Background

MainActivity.java

package com.test.myapplication;

import android.app.ProgressDialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button button;
    private ProgressDialog dialog;
    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override             
public void onClick(View v) {
                dialog = new ProgressDialog(MainActivity.this);
                dialog.getWindow().setBackgroundDrawable(new 
 ColorDrawable(android.graphics.Color.TRANSPARENT));
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                dialog.show();
                dialog.setContentView(R.layout.my_progress);
            }
        });

    }
}

In res/layout 
activity_main.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="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context="com.test.myapplication.MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click"
        android:textSize="20sp" />
</RelativeLayout>
 
 
In res/layout 
 my_progress.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@android:color/transparent">

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:indeterminateDrawable="@drawable/myprogress_style" />

</RelativeLayout> 
 
 

In res/drawable
myprogress_style.xml
 
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360">

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false">

        <gradient
            android:centerColor="#FFCC35"
            android:centerY="0.50"
            android:endColor="#CE0000"
            android:startColor="#CE0000"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>


Now Run the application.
Try It...

Friday 9 October 2015

Android CardView Example

Android 5.0 (Lollipop), Google introduced two new Widgets: RecyclerView and CardView. The RecyclerView is a more advanced and more flexible version of the ListView. This new component is a big step because the ListView is one of the most used UI widgets. The CardView widget, on the other hand, is a new component that does not "upgrade" an existing component.



Before starting off don’t forget to include these dependencies in your app gradle.

build.gradle

dependencies {

    compile 'com.android.support:appcompat-v7:23.0.0'

    compile 'com.android.support:cardview-v7:23.0.0'

    compile 'com.android.support:recyclerview-v7:23.0.0'

}


Next please a look at activity layout, which shows the RecyclerView:

activity_main.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="match_parent"  
tools:context=".CardViewActivity">

<android.support.v7.widget.RecyclerView      
android:id="@+id/my_recycler_view"      
android:layout_width="match_parent"      
android:layout_height="match_parent"      
android:scrollbars="vertical"/>

</RelativeLayout>



In this Android CardView Example, we will use this object for supplying the data to adapter:
DataObject.java

package com.example.cardview;


public class DataObject {
    private String mText1;
    private String mText2;

    DataObject (String text1, String text2){
        mText1 = text1;
        mText2 = text2;
    }

    public String getmText1() {
        return mText1;
    }

    public void setmText1(String mText1) {
        this.mText1 = mText1;
    }

    public String getmText2() {
        return mText2;
    }

    public void setmText2(String mText2) {
        this.mText2 = mText2;
    }
}


 Lets have a look at the card_view_row.xml

 card_view_row.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="match_parent">

<android.support.v7.widget.CardView      
android:id="@+id/card_view"      
android:focusable="true"      
android:clickable="true"      
android:foreground="?android:attr/selectableItemBackground"      
android:layout_width="fill_parent"      
android:layout_height="100dp"      
android:layout_gravity="center"      
android:layout_margin="5dp">

<RelativeLayout          
android:layout_width="fill_parent"          
android:layout_height="fill_parent">

<TextView              
android:id="@+id/textView"              
android:layout_width="wrap_content"              
android:layout_height="wrap_content"              
android:layout_alignParentTop="true"              
android:textStyle="bold" />

<TextView              
android:id="@+id/textView2"              
android:layout_width="wrap_content"              
android:layout_height="wrap_content"              
android:layout_below="@+id/textView"              
android:layout_marginTop="10dp" />

</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>


The activity below shows the CardView list:

MainActivity.java

package com.example.cardview;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private static String LOG_TAG = "CardViewActivity";
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyRecyclerViewAdapter(getDataSet());
        mRecyclerView.setAdapter(mAdapter);
    }
    @Override    protected void onResume() {
        super.onResume();
        ((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
                .MyClickListener() {
            @Override            public void onItemClick(int position, View v) {
                Log.i(LOG_TAG, " Clicked on Item " + position);
                Toast.makeText(MainActivity.this,"clicked on item:"+position,Toast.LENGTH_SHORT).show();
            }
        });
    }

    private ArrayList<DataObject> getDataSet() {
        ArrayList results = new ArrayList<DataObject>();
        for (int index = 0; index < 20; index++) {
            DataObject obj = new DataObject("Heading Text " + index,
                    "Sub Text " + index);
            results.add(index, obj);
        }
        return results;
    }
}


Next lets have a look at the main class where RecyclerView adapter is defined. This class shows how to include an Android CardView widget in a RecyclerView:

MyRecyclerViewAdapter.java

package com.example.cardview;


import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.ArrayList;


public class MyRecyclerViewAdapter extends RecyclerView
        .Adapter<MyRecyclerViewAdapter
        .DataObjectHolder> {
    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private ArrayList<DataObject> mDataset;
    private static MyClickListener myClickListener;

    public static class DataObjectHolder extends RecyclerView.ViewHolder
            implements View
            .OnClickListener {
        TextView label;
        TextView dateTime;

        public DataObjectHolder(View itemView) {
            super(itemView);
            label = (TextView) itemView.findViewById(R.id.textView);
            dateTime = (TextView) itemView.findViewById(R.id.textView2);
            Log.i(LOG_TAG, "Adding Listener");
            itemView.setOnClickListener(this);
        }

        @Override        public void onClick(View v) {
            myClickListener.onItemClick(getAdapterPosition(), v);
        }
    }

    public void setOnItemClickListener(MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
        mDataset = myDataset;
    }

    @Override    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_row, parent, false);

        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.label.setText(mDataset.get(position).getmText1());
        holder.dateTime.setText(mDataset.get(position).getmText2());
    }

    public void addItem(DataObject dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

    @Override    public int getItemCount() {
        return mDataset.size();
    }

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }
}


This would give an output screen with CardViews like these:



Tuesday 15 September 2015

Android Cutom Listview with image and text


Android Cutom Listview with image and text

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="${relativePackage}.${activityClass}" >

     <ListView
       android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" >
    </ListView>

</RelativeLayout>
 ________________________________________________________

Create list_item.xml under res/layout
list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp" >
   
<TableRow>
        <ImageView
            android:id="@+id/img"
            android:layout_width="50dp"          
            android:layout_height="50dp"/>

        <TextView
            android:id="@+id/txt"
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="50dp" />
</TableRow>

</TableLayout>
 ______________________________________________________
Create a class for custom list
CustomList.java

package com.example.customlistview;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomList extends ArrayAdapter<String> {

    private final Activity context;
    private final String[] web;
    private final Integer[] imageId;

    public CustomList(Activity context, String[] web, Integer[] imageId) {
        super(context, R.layout.list_item, web);
        this.context = context;
        this.web = web;
        this.imageId = imageId;

    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.list_item, null, true);
        TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);

        ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
        txtTitle.setText(web[position]);

        imageView.setImageResource(imageId[position]);
        return rowView;
    }
}
 _____________________________________________________

In MainActivity.java

package com.example.customlistview;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    ListView list;
    String[] web = {
        "Acer","Dell","Lenovo"
    } ;
    Integer[] imageId = {
            R.drawable.one,
            R.drawable.two,
            R.drawable.three
         

    };

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

        CustomList adapter = new
                CustomList(MainActivity.this, web, imageId);
        list=(ListView)findViewById(R.id.list);
                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();

                    }
                });

    }

}

_______________________________________________________

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.customlistview"
    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=".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>

Screenshots



More news about Android 
https://www.facebook.com/Code.in.Android






Wednesday 19 August 2015

How to write files from Asset folder to Sd card in Android

Call copyAssets() method from MainActivity.

public class MainActivity extends Activity{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

 copyAssets();
}

//Method to copy filename.ext from assets to sdcard.
private void copyAssets()
{
      AssetManager assetManager = getAssets();
      String[] files = null;
      InputStream in = null;
      OutputStream out = null;
      String filename = "filename.ext";
      try
      {
            in = assetManager.open(filename);
            out = new FileOutputStream("/sdcard/" + filename);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
      }
      catch(IOException e)
      {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
      }     
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
      byte[] buffer = new byte[1024];
      int read;
      while((read = in.read(buffer)) != -1)
      {
            out.write(buffer, 0, read);
      }
}

}

Note: Don't forget to add permission in AndroidManifest.xml

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

Thursday 9 July 2015

Android Fragment Example

Android Fragment Example with List in One fragment and selected value displays in the Second fragment

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="horizontal"
    tools:context="com.example.fragmentproject.MainActivity">

    <fragment
        android:id="@+id/fragment"
        android:layout_width="170dp"
        android:layout_height="match_parent"
        class="com.example.fragmentproject.MenuFragment" />

    <fragment
        android:id="@+id/fragment2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.example.fragmentproject.TextFragment" />

</LinearLayout>


list_fragemnt.xml (fragment for list)

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/list" />
</LinearLayout>


text_fragment.xml (fragment to display toast)

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40px"
        android:textColor="#ffffff"
        android:layout_gravity="center"
        android:id="@+id/AndroidOs"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="30px"
        android:id="@+id/Version"/>

</LinearLayout>


MainActivity.java

package com.example.fragmentproject;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}


MenuFragment.java

package com.example.fragmentproject;


import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MenuFragment extends ListFragment {

    String[] AndroidOS = new String[] { "Cupcake","Donut","Eclair","Froyo","Gingerbread","Honeycomb","Ice Cream SandWich","Jelly Bean","KitKat" };

    String[] Version = new String[]{"1.5","1.6","2.0-2.1","2.2","2.3","3.0-3.2","4.0","4.1-4.3","4.4"};

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.list_fragment, container, false);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, AndroidOS);
        setListAdapter(adapter);
        return view;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        TextFragment txt = (TextFragment)getFragmentManager().findFragmentById(R.id.fragment2);
        txt.change(AndroidOS[position],"Version : "+Version[position]);
        getListView().setSelector(android.R.color.holo_blue_dark);
    }
}


TextFragment.java

package com.example.fragmentproject;

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

public class TextFragment extends Fragment {
    TextView text,vers;

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.text_fragment, container, false);
        text= (TextView) view.findViewById(R.id.AndroidOs);
        vers= (TextView)view.findViewById(R.id.Version);
        return view;
    }
    public void change(String txt, String txt1){
        text.setText(txt);
        vers.setText(txt1);

    }
}

Screenshots

Run the project, the output appears on the mobile screen.



Tuesday 3 March 2015

Android Spinner Example

Android Spinner and Toast displays the selected item in a Spinner.

Main Layout Xml

spinner_page.xml

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

    <Spinner
        android:id="@+id/spversions"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />

</RelativeLayout>



MainActivity File

SpinnerPage.java

package com.example.spinner;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class SpinnerPage extends Activity implements OnItemSelectedListener {
    private Spinner spversions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.spinner_page);
        spversions = (Spinner) findViewById(R.id.spversions);

        String[] android_versions = { "Cupcake", "Donut", "Eclair", "Froyo",
                "Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean",
                "KitKat", "Lolipop" };

        ArrayAdapter<String> adapter_versions = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, android_versions);

        adapter_versions
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spversions.setAdapter(adapter_versions);
        spversions.setOnItemSelectedListener(this);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub
        spversions.setSelection(position);
        String selected_version = (String) spversions.getSelectedItem();
        Toast.makeText(getApplicationContext(),
                "Selected item:" + selected_version, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub

    }
}












Screen Shots

Selected item displays in a Toast



Android ListView

Android ListView with Toast displaying the Item selected.


MainLayout File

list_view_page.xml

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

    <ListView
        android:id="@+id/listversions"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</RelativeLayout>


ListView row TextView from different xml file (res/layout/samplerow.xml)

samplerow.xml 

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="15sp" >

</TextView>



Java Code in MainActivity oncreate method

ListViewPage.java

package com.example.listview;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ListViewPage extends Activity {
    private ListView samplelistview;
    private ArrayAdapter<String> listadapter;

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

        // Find the Listview resource
        samplelistview = (ListView) findViewById(R.id.listversions);

        // Create List of android versions
        String[] android_versions = { "Cupcake", "Donut", "Eclair", "Froyo",
                "Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean",
                "KitKat", "Lolipop" };
        ArrayList<String> androidlist = new ArrayList<String>();
        androidlist.addAll(Arrays.asList(android_versions));

        // create array adapter for androidlist
        listadapter = new ArrayAdapter<String>(this, R.layout.samplerow,
                androidlist);

        // set array adapter as ListView's adapter
        samplelistview.setAdapter(listadapter);

        samplelistview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                String Item_clicked = parent.getItemAtPosition(position)
                        .toString();
                Toast.makeText(getApplicationContext(),
                        "Version Selected:" + Item_clicked, Toast.LENGTH_SHORT)
                        .show();

            }
        });

    }
}


Screen Shots:
 Run the application.



Click on the item in the list, Toast displays the selected item.







Tuesday 24 February 2015

AutoComplete TextBox in Android

In this blog, I will show how to achieve AutoComplete TextBox property, and how it works.

Java Code:


MainActivity.java

package com.example.autocomplete;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements TextWatcher {
    AutoCompleteTextView autocomplete;
    ListView listview;
    ArrayList<String> listitems = new ArrayList<String>();
    SQLiteDatabase sqlitedatabase;
    Button save, cancel;

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

        sqlitedatabase = this
                .openOrCreateDatabase("sample", MODE_PRIVATE, null);
        try {
            sqlitedatabase
                    .execSQL("create table if not exists student(name varchar(30))");
                   } catch (Exception e) {
            System.err.println("error" + e.toString());
        }
        save = (Button) findViewById(R.id.btnsave);
        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String value = autocomplete.getText().toString();
                try {
                    sqlitedatabase.execSQL("insert into student (name) values('"
                            + value + "')");
                    Toast.makeText(getApplicationContext(), "value stored",
                            Toast.LENGTH_SHORT).show();
                                      Intent intent = new Intent(MainActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                } catch (Exception ex) {
                    System.err.println("error");
                }

            }
        });
        cancel = (Button) findViewById(R.id.btncancel);
        cancel.setOnClickListener(new OnClickListener() {

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

            }
        });
        Cursor c = sqlitedatabase.rawQuery("select distinct name from student",
                null);

        if (c != null) {
            if (c.moveToFirst()) {
                do {
                    String Auto = c.getString(c.getColumnIndex("name"));
                    listitems.add(Auto);
                } while (c.moveToNext());
            }

        }
        c.close();

        final String[] arrayOfStrings;
        arrayOfStrings = listitems.toArray(new String[listitems.size()]);
        autocomplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        autocomplete.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                arrayOfStrings));

    }

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

    }
}


activity_main.xml

  <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_margin="10dp"
        android:completionThreshold="1"
        android:ems="10" >

        <requestFocus />
    </AutoCompleteTextView>

    <TextView
        android:id="@+id/txtviewenter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="30dp"
        android:paddingRight="2dp"
        android:text="Enter Text"
        android:textSize="20sp" />

    <LinearLayout
        android:id="@+id/buttonlayout"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_margin="5dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnsave"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="Save"
            android:textSize="20sp"
            android:textStyle="bold" >
        </Button>

        <Button
            android:id="@+id/btncancel"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="Cancel"
            android:textSize="20sp"
            android:textStyle="bold" >
        </Button>
    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="invisible" />


 Screen Shots:

 Save text in Local database.

Again open the application, try to enter the text, the available words starts with the letter entered pop ups.













Monday 23 February 2015

Android Camera Application

In this blog, I will show how to use default camera application in our application

Java Code:

Sample.java

package com.example.eventorganize;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class Sample extends Activity {
    ImageView imgphoto;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);
        imgphoto = (ImageView) findViewById(R.id.imgphoto);
        imgphoto.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                capture();
            }
        });
    }
    protected void capture() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 0);
    }
   
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.err.println("code:" + data);
        if (data != null) {
            Bitmap bp = (Bitmap) data.getExtras().get("data");
            imgphoto.setImageBitmap(bp);
        }
    }
}


activity_sample.xml

 <ImageView
        android:id="@+id/imgphoto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:background="@drawable/capture"
        android:contentDescription="@string/app_name"
        android:scaleType="fitXY" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/tap"
        android:textAppearance="?android:attr/textAppearanceLarge" />


strings.xml

<string name="tap">Tap here to capture Photo</string>


Screen Shots: