0%
Loading ...

Android Tutorials

This category contains all the tutorials related to Android app development.

Delete data from SQLite database

In this tutorial, we’ll explore the process of deleting data from an SQLite database, building on our previous lesson where we covered updating data in the database. Specifically, we’ll focus on enhancing our Phone Book app by adding functionality to delete contact numbers. In our prior tutorial, we implemented a popup triggered by clicking a list item, offering two choices: update and delete. In this tutorial, we’ll guide you through the steps to delete a contact when the user selects the delete option. Let’s dive into the process of efficiently managing and modifying your SQLite database. To initiate the deletion of data, our first step involves introducing a new method named deleteData() within the DatabaseHelper class. This method serves as a crucial component in our process of removing specific records from the database. Take a look at the following code snippet to integrate this functionality into your application. DatabaseHelper Class Code: Following the implementation of the deleteData() method in our DatabaseHelper class, the subsequent action involves invoking this method in our main class when the user opts for the delete option within the popup. Please check out the provided code snippet to integrate this functionality into your main class. MainActivity Java Code: Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Delete data from SQLite database Read More »

Update Data in SQLite Database

In this tutorial, we will learn about how to Update data in SQLite Database. In the last tutorial, we have learned how to fetch data from the SQLite database. In this tutorial, we will update existing contacts. We will show a popup with options update and delete when a user will click on the list item. If a user will choose update option then we will show a new activity called UpdateContact where a user can update contact. First of all, we will show and popup when a user will click on an item of listView. To show popup first step is to add make a new file in res/menu (if there is no menu resource folder create a new menu folder by right-clicking on res) with options check this code: Menu XML code: <?xml version=”1.0″ encoding=”utf-8″?> <menu xmlns:android=”http://schemas.android.com/apk/res/android”> <item android:id=”@+id/update” android:title=”Update” /> <item android:id=”@+id/delete” android:title=”Delete” /> </menu> After this we will write code in MainActivity to show popup on list item click and to open UpdateContact activity on choose of Update option in popup. MainActivity Java Code: public class MainActivity extends AppCompatActivity { ListView listView; DatabaseHelper databaseHelper; List<contactmodel> contactList=new ArrayList<contactmodel>(); int i=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); databaseHelper = new DatabaseHelper(getApplicationContext()); Cursor cursor = databaseHelper.getData(); String namesArray[] = new String[cursor.getCount()]; while (cursor.moveToNext()) { namesArray[i] = cursor.getString(cursor.getColumnIndex(“NAME”)); contactList.add(new ContactModel(cursor.getInt(cursor.getColumnIndex(“ID”)),cursor.getString(cursor.getColumnIndex(“NAME”)),cursor.getString(cursor.getColumnIndex(“CONTACT”)))); i++; } ArrayAdapter<string> arrayAdapter = new ArrayAdapter<>(getApplication(), android.R.layout.simple_list_item_1, namesArray); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<!–?–> adapterView, View view,final int i, long l) { PopupMenu popup = new PopupMenu(getApplicationContext(), view); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.popup_menu, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case R.id.update: Intent intent=new Intent(getApplicationContext(),UpdateContact.class); intent.putExtra(“ID”,contactList.get(i).getId()); intent.putExtra(“NAME”,contactList.get(i).getName()); intent.putExtra(“CONTACT”,contactList.get(i).getNumber()); startActivity(intent); break; case R.id.delete: break; } return true; } }); popup.show(); } }); } } Now we will write code in layout file of UpdateContact activity. Check this code: UpdateContact Activity XML Code: <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:app=”http://schemas.android.com/apk/res-auto” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:orientation=”vertical” android:padding=”16dp” tools:context=”.UpdateContact”> <EditText android:layout_width=”match_parent” android:layout_height=”50dp” android:id=”@+id/nameET” android:hint=”Please Enter Name”/> <EditText android:layout_width=”match_parent” android:layout_height=”50dp” android:id=”@+id/contactET” android:hint=”Please Enter Contact Number”/> <Button android:layout_width=”match_parent” android:layout_height=”50dp” android:id=”@+id/updateContactB” android:text=”Update Contact”/> </LinearLayout> Now we will define a new method in DatabaseHelper to update contact information. check this code: DatabaseHelper class code: public class DatabaseHelper extends SQLiteOpenHelper { //writing database name private static final String DATABASE_NAME = “PhoneBook.db”; //writing table name private static final String TABLE_NAME = “Contacts_Table”; //Constructor here public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } //On create and onUpgrade these two are abstract methods in SQLiteOpenHelper class @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { //use this execSQL method to create new table in database sqLiteDatabase.execSQL(“CREATE TABLE ” + TABLE_NAME + ” (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT , CONTACT TEXT )”); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } //Creating this method to insert data in the table public boolean insertData(String name, String contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(“NAME”, name); cv.put(“CONTACT”, contact); long result = db.insert(TABLE_NAME, null, cv); if (result == -1) { return false; } else { return true; } } //getData method to fetch data from SQLite database public Cursor getData() { SQLiteDatabase db = this.getWritableDatabase(); String query = “SELECT * FROM ” + TABLE_NAME; Cursor cursor = db.rawQuery(query, null); return cursor; } //updateData method to update contact info public int updateData(int id, String name, String contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(“NAME”, name); contentValues.put(“CONTACT”, contact); int i = db.update(TABLE_NAME, contentValues, “ID =” + id, null); return i; } } Now we will write code in java file of UpdateContact activity to update contact information in SQLite database. UpdateContact Activity Java Code: public class UpdateContact extends AppCompatActivity { EditText nameET, contactET; Button updateContactB; DatabaseHelper databaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_contact); nameET=(EditText)findViewById(R.id.nameET); contactET=(EditText)findViewById(R.id.contactET); updateContactB=(Button)findViewById(R.id.updateContactB); databaseHelper=new DatabaseHelper(getApplicationContext()); Bundle bundle=getIntent().getExtras(); final int id=bundle.getInt(“ID”); String name=bundle.getString(“NAME”); final String contact=bundle.getString(“CONTACT”); nameET.setText(name); contactET.setText(contact); updateContactB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { databaseHelper.updateData(id,nameET.getText().toString(),contactET.getText().toString()); startActivity(new Intent(getApplicationContext(),MainActivity.class)); } }); } }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Update Data in SQLite Database Read More »

Fetch Data from SQLite Database

In this tutorial, we will learn about how to fetch data from SQLite Database. In the last tutorial, we learned how to add data in the SQLite database in this tutorial we will fetch data from the database. we will continue with the same app which we started in the last tutorial. In this tutorial, we will fetch data from and SQLite and will show data in the form of a list in MainActivity. We will start with the layout file of the main activity and add a listview. MainActivity XML Code: <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:app=”http://schemas.android.com/apk/res-auto” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” tools:context=”.MainActivity”> <ListView android:layout_width=”match_parent” android:layout_height=”match_parent” android:id=”@+id/listView” /> </LinearLayout> Before going to java file of MainActivity. We will add a method in DatabaseHelper class to which would help us to fetch data from SQLite database. Check this code: DatabaseHelper Class Code: public class DatabaseHelper extends SQLiteOpenHelper { //writing database name private static final String DATABASE_NAME = “PhoneBook.db”; //writing table name private static final String TABLE_NAME = “Contacts_Table”; //Constructor here public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } //On create and onUpgrade these two are abstract methods in SQLiteOpenHelper class @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { //use this execSQL method to create new table in database sqLiteDatabase.execSQL(“CREATE TABLE ” + TABLE_NAME + ” (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT , CONTACT TEXT )”); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } //Creating this method to insert data in table public boolean insertData(String name, String contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(“NAME”, name); cv.put(“CONTACT”, contact); long result = db.insert(TABLE_NAME, null, cv); if (result == -1) { return false; } else { return true; } } //getMethod defined to get data from SQLite database public Cursor getData() { SQLiteDatabase db = this.getWritableDatabase(); String query = “SELECT * FROM ” + TABLE_NAME; Cursor cursor = db.rawQuery(query, null); return cursor; } } As you can see we have added getData() method in DatabaseHelper class to fetch data from the SQLite database. Here you can see I have used a new class called Cursor it is same as ResultSet in core java. Now we will create a model class for Contact called ContactModel which would later help us to save data in the form of a list. check this code of model class: ContactModel Class Code: public class ContactModel { int id; String name; String number; public ContactModel(int id, String name, String number) { this.id = id; this.name = name; this.number = number; } public int getId() { return id; } public String getName() { return name; } public String getNumber() { return number; } } After this step is our next step is to call this getData() method call in MainActivity and to show data in our ListView of MainActivity. Check this code here: MainActivity Java Code: public class MainActivity extends AppCompatActivity { ListView listView; DatabaseHelper databaseHelper; List<contactmodel> contactList=new ArrayList<contactmodel>(); String namesArray[]; int i=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView=(ListView)findViewById(R.id.listView); databaseHelper=new DatabaseHelper(getApplicationContext()); Cursor cursor=databaseHelper.getData(); namesArray=new String[cursor.getCount()]; while (cursor.moveToNext()){ namesArray[i]=cursor.getString(cursor.getColumnIndex(“NAME”)); contactList.add(new ContactModel(cursor.getInt(cursor.getColumnIndex(“ID”)),cursor.getString(cursor.getColumnIndex(“NAME”)),cursor.getString(cursor.getColumnIndex(“CONTACT”)))); i++; } ArrayAdapter<string> arrayAdapter=new ArrayAdapter<>(getApplication(),android.R.layout.simple_list_item_1,namesArray); listView.setAdapter(arrayAdapter); } }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Fetch Data from SQLite Database Read More »

Insert data in SQLite database

In this tutorial, we will learn about how to Insert Data in SQLite. Here we will start a new application called Phone Book to save contact number. Our first step would be to create a new SQLite database and table to save our contact details on the device. After that in upcoming tutorials, we will fetch, update and delete data in the SQLite database. Please follow all the steps: First of all, we need an Activity to add a new contact in our database so I will create a new Activity called AddContact. Check the code of layout file and java file here. AddContact Activity XML Code: <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:app=”http://schemas.android.com/apk/res-auto” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:orientation=”vertical” android:padding=”16dp” tools:context=”.AddContact”> <EditText android:layout_width=”match_parent” android:layout_height=”50dp” android:id=”@+id/nameET” android:hint=”Please Enter Name”/> <EditText android:layout_width=”match_parent” android:layout_height=”50dp” android:id=”@+id/contactET” android:hint=”Please Enter Contact Number”/> <Button android:layout_width=”match_parent” android:layout_height=”50dp” android:id=”@+id/addContactB” android:text=”ADD CONTACT”/> </LinearLayout> Our next step is to write code in Java file of this activity but before writing code in Java file of AddContact Activity. I will make another class to handle SQLite database operations(table creation, insertion, deletion, updating etc). Create a new class called DatabaseHelper. DatabaseHelper class code: public class DatabaseHelper extends SQLiteOpenHelper { //writing database name private static final String DATABASE_NAME = “PhoneBook.db”; //writing table name private static final String TABLE_NAME = “Contacts_Table”; //Constructor here public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } //On create and onUpgrade these two are abstract methods in SQLiteOpenHelper class @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { //use this execSQL method to create new table in database sqLiteDatabase.execSQL(“CREATE TABLE ” + TABLE_NAME + ” (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT , CONTACT TEXT )”); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } //Creating this method to insert data in a table public boolean insertData(String name, String contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(“NAME”, name); cv.put(“CONTACT”, contact); long result = db.insert(TABLE_NAME, null, cv); if (result == -1) { return false; } else { return true; } } } Here you can see we have written several lines in our DatabaseHelper class. First of all, inherit class called SQLiteOpenHelper in our class and then we have created a constructor and after that, we implemented two abstract methods of SQLiteOpenHelper class. Apart from this, we have created our own method to insert data in the database. After writing code in DatabaseHelper class we will go back to AddContact activity and now we will write code in Activity Java file. Check this code: AddContact Activity code: public class AddContact extends AppCompatActivity { EditText nameET, contactET; Button addContactB; DatabaseHelper databaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_contact); nameET=(EditText)findViewById(R.id.nameET); contactET=(EditText)findViewById(R.id.contactET); addContactB=(Button)findViewById(R.id.addContactB); databaseHelper=new DatabaseHelper(getApplicationContext()); addContactB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String nameS=nameET.getText().toString(); String contactS=contactET.getText().toString(); boolean result=databaseHelper.insertData(nameS,contactS); if(result) Toast.makeText(getApplicationContext(),”Done”,Toast.LENGTH_SHORT).show(); else Toast.makeText(getApplicationContext(),”Error”,Toast.LENGTH_SHORT).show(); } }); } } Here you can see we have called a function insertData of which we created in DatabaseHelper class to insert data in the database. After that, we showed the result Done if data will enter successfully and Error in the case of any problem. In the next tutorial, we will fetch data from the database and will show data in another activity. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Insert data in SQLite database Read More »

What is SQLite in Android

In this tutorial we will learn about what is SQLite Database. Android provides the facility to use the SQLite database to store data on the device in the form of the file. SQLite is an open-source SQL database. Furthermore, it is so easy to use SQLite we can access data from the database without even establishing a connection with the database. Apart from this In android, there is a dedicated package to work with SQLite database. SQLite package: As I mention in previous paragraph that Android has dedicated package to work with SQLIte which is android.database.sqlite. This package have various classes which makes it so easy to use SQLIte in a application What we will do: In upcoming tutorials we will see how to create new SQLite database in device and how to perform operations like: Insert Data in Database Fetch Data from Database Update Data in Database Delete Data from Database To learn this we will create a small application called Phone Book in which we will store contact number. So stay connected and follow all the upcoming tutorials.   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

What is SQLite in Android Read More »

RecyclerView in Android

In this tutorial, we will learn about RecyclerView in Android. Recycler view is introduced from android 6.0(Marshmallow). RecyclerView is used to create a list or grids in android. You can say it RecyclerView is the next version of ListView. RecyclerView provides much better performance than ListView. Here we will create simple RecyclerView. Info! Please follow each step carefully. Implement Dependencies: Our first step would be to add two dependencies in our project. so add these two given dependencies in your Gradle (Module: app). implementation ‘com.android.support:recyclerview-v7:26.1.0′ Now write the following code in main_activity.xml to add RecyclerView in activity. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” xmlns:app=”http://schemas.android.com/apk/res-auto” android:layout_width=”match_parent” android:layout_height=”match_parent” app:layout_behavior=”@string/appbar_scrolling_view_behavior” tools:showIn=”@layout/activity_main” tools:context=”.MainActivity”> <android.support.v7.widget.RecyclerView android:id=”@+id/recycler_view” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:scrollbars=”vertical” /> </RelativeLayout> Our next step is to create model. Name this class as DataModel.java.(Model totally depends upon the requirements of project. Here we are just taking two variables title and description in model). public class DataModel { private String post_title; private String post_description; public TopicTitleModel(String post_title, String post_description) { this.post_title = post_title; this.post_description = post_description; } public String getPost_title() { return post_title; } public String getPost_description(){ return post_description; } } Our next step is to create layout for recyclerView item. Design is totally depends upon the project requirements. Here we are just creating simple layout to show title and description. we named this layout as single_item_layout.xml. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:clickable=”true” android:focusable=”true” android:orientation=”vertical” android:padding=”16dp” > <TextView android:id=”@+id/title” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:layout_alignParentTop=”true” android:textSize=”16dp” android:textStyle=”bold” /> <TextView android:id=”@+id/description” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:layout_below=”@id/title” /> </RelativeLayout> After creating single_item_layout.xml our next step is to create a Adapter for RecyclerView. We named this adapter as PostAdapter.java. public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> { List<DataModel> list=new ArrayList<>(); Context context; public TitlesAdapter(List<DataModel> list, Context context){ this.list=list; this.context=context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View v= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_item_layout,viewGroup,false); return new ViewHolder(v); } public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) { viewHolder.text.setText(list.get(i).getPost_title()); viewHolder.description.setText(list.get(i).getPost_description()); } @Override public int getItemCount() { return list.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ TextView text; TextView description; public ViewHolder(@NonNull View itemView) { super(itemView); text=itemView.findViewById(R.id.title); description=itemView.findViewById(R.id.description); } } } No we reached at our final step. In this step we will get Recycler we in MainActivity.java then we will set adapter and LayoutManager to RecyclerView. public class MainActivity extends AppCompatActivity { private List<DataModel> list = new ArrayList<>(); private RecyclerView recyclerView; private PostAdapter postAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); postAdapter = new PostAdapter(movieList,getApplication()); prepareData(); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(postAdapter); } private void prepareData() { list.add(new DataModel(“Color Red”,”Apple is Red”)); list.add(new DataModel(“Color Blue”,”Sky is Blue”)); list.add(new DataModel(“Color Green”,”Grass is Green”)); } }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

RecyclerView in Android Read More »

ListView in Android

In this tutorial, we will learn about ListView in Android. ListView is one of the most commonly used widgets. We normally see ListView in different Android Apps, for example, contact list. Here, we will learn how we can create a simple list in Android and how we can create a custom ListView in Android. First of all we will add ListView Widget in XML layout file. Check this code. XML Code: <?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” tools:context=”.MainActivity”> <ListView android:layout_height=”match_parent” android:layout_width=”match_parent” android:id=”@+id/listView” /> </LinearLayout> To add listView in Activity we need an adapter which will help us to merge data and view together in ListView. We can provide data to list in the format of array or list. Here we will add simple ArrayAdapter. Check this Java code. Java Code: public class MainActivity extends AppCompatActivity { String colors[]={“Red”,”Green”,”Blue”}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ListView listView=findViewById(R.id.listView); ArrayAdapter<String> arrayAdapter=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,colors); listView.setAdapter(arrayAdapter); } } Here is output after writing all this code. Custom ListView in Android: To make a custom ListView in android first of all we have to create a layout for single item of list and then we have to create a custom adapter to create listview. Here you have to crate new layout file. Here I just create new layout file and named it as list_item_layout Check this code to create a custom list item. List Item XML Code: <?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=”wrap_content”> <TextView android:layout_width=”match_parent” android:layout_height=”wrap_content” android:textSize=”18dp” android:textColor=”@color/colorPrimaryDark” android:id=”@+id/text1″/> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:textSize=”14dp” android:id=”@+id/text2″/> </LinearLayout> After creating this layout file we will create custom adpater to add data in this custom list view. To create a custom adapter just add a new java class in your android project and inherit BaseAdapter class in this class. BaseAdapter is an abstract class it mean you have to override all the abstract methods of this class into user class. Here i will create new class called MyListAdapter to create a custom adapter check this code Custom Adapter Java Code: public class MyListAdpater extends BaseAdapter { String array1[]={“Red”,”Blue”,”Green”}; String array2[]={“Rose is Red”,”Sky is Blue”,”Grass is Green”}; LayoutInflater layoutInflater; public MyListAdpater(Context context){ layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return array1.length; } @Override public Object getItem(int i) { return i; } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { View v=layoutInflater.inflate(R.layout.list_item_layout,null,false); TextView text1=v.findViewById(R.id.text1); TextView text2=v.findViewById(R.id.text2); text1.setText(array1[i]); text2.setText(array2[i]); return v; } } Here our custom list item design is ready and our adapter is also ready. Now we will change the adapter of our listview from ArrayAdapter to MyListAdapter in MainActivity. Main Activity Java Code: public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ListView listView=findViewById(R.id.listView); MyListAdpater myListAdpater=new MyListAdpater(getApplicationContext()); listView.setAdapter(myListAdpater); } } check this Output after adding CustomAdapter to our ListView. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

ListView in Android Read More »

WebView in Android

In this tutorial, we will learn how to use a WebView in Android. We use WebView to show webpages in Android. Using WebView you can load a web page from the same application or you can load a web page from any URL. To use web view in android you must have internet permission in your android manifest file. In this tutorial, we will learn how to add WebView in Android XML file and how to load URL in this WebView using our Java file. Before doing anything we will add internet permission in our AndroidManifest.xml file. Because without Internet permission our web view will not work. Add in Manifest file: <uses-permission android:name=”android.permission.INTERNET”/> Now we will move to our next step. So start with our XML file. In this step, we will add a Web View widget in our activity. XML Code: <?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” tools:context=”.MainActivity”> <WebView android:id=”@+id/webView” android:layout_width=”match_parent” android:layout_height=”match_parent” /> </LinearLayout> After adding this XML code in XML layout file add this code to Java file where we will write code to load a web page in our WebView. Java Code: public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final WebView webView=findViewById(R.id.webView); webView.loadUrl(“https://www.google.com”); } } After adding this code in Java file run project and you will get Google Home page on your activity because we have written URL of google in loadURL method of WebView class. Here you can try to load different URLs. Check Output of this project. Output: Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

WebView in Android Read More »

RatingBar in Android

In this tutorial, we will learn how to use RatingBar in Android. RatingBar is used to get the rating from users. User can give rating by clicking on starts. When the user clicks on starts of Ratingbar it returns float value like 2.5, 1.0, 4.5 etc. In this tutorial, we will learn how to add Ratingbar in the XML layout file. How to get Rating in Java file. First of all, we will write our layout file code. In the layout file, we will add a RatingBar widget and a button. After that, we will write code in Java file to get rating given by the user on button click. Check this XML code. XML Code: <?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” android:padding=”16dp” tools:context=”.MainActivity”> <RatingBar android:id=”@+id/ratingbar” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:saveEnabled=”true” android:numStars=”5″ android:layout_marginBottom=”10dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Submit” android:id=”@+id/submit”/> </LinearLayout> After writing this code we will write code in our java file to fetch rating given by the user. Java Code: public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final RatingBar ratingBar=findViewById(R.id.ratingbar); final Button button=findViewById(R.id.submit); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { float rating=ratingBar.getRating(); Toast.makeText(getApplicationContext(),rating+””,Toast.LENGTH_SHORT).show(); } }); } } Output: Here is the output after writing this code. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

RatingBar in Android Read More »

SeekBar in Android

In this tutorial, we will learn how to use SeekBar in Android. The Seekbar is a child class of AbsSeekBar class. Seekbar is kind of progress bar and Seekbar allow users to move thumb of Seekbar from left or right. For example, in media players, you can move the song forward or backwards by moving a Seekbar. Here we will learn how to add SeekBar in the XML layout file and how to get change listener of SeekBar in android Java file. XML Code: <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:app=”http://schemas.android.com/apk/res-auto” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:padding=”16dp” android:orientation=”vertical” android:gravity=”center” tools:context=”.MainActivity”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”0″ android:layout_marginBottom=”15dp” android:id=”@+id/textView” android:textSize=”18sp”/> <SeekBar android:layout_width=”match_parent” android:layout_height=”wrap_content” android:id=”@+id/seekBar”/> </LinearLayout> Output: After creating this XML layout file we will move to our Java file In this file we will use seekbar change listener to track the change in seekbar. Java Code: public class MainActivity extends AppCompatActivity { SeekBar seekBar; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); seekBar=(SeekBar)findViewById(R.id.seekBar); textView=(TextView)findViewById(R.id.textView); textView.setTextColor(Color.BLACK); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { textView.setText(progress+””); } @Override public void onStartTrackingTouch(SeekBar seekBar) { textView.setTextColor(Color.GREEN); } @Override public void onStopTrackingTouch(SeekBar seekBar) { textView.setTextColor(Color.BLACK); } }); } }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

SeekBar in Android Read More »

Scroll to Top
×