Android Lab Project

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

1.Create activity and debug the App.

Android Studio provides a debugger that allows you to do the following and
more:Select a device to debug your app on. Set breakpoints in your Java,
Kotlin, and C/C++ code.Examine variables and evaluate expressions at
runtime.This page includes instructions for basic debugger operations. For
more documentation, also see the IntelliJ IDEA debugging docs.
Run a debuggable build variant:
You must use a build variant that includes debuggable true in the build
configuration. Usually, you can just select the default "debug" variant that's
included in every Android Studio project (even though it's not visible in the
build.gradle file). But if you define new build types that should be debuggable,
you must add `debuggable true` to the build type:
Java coding
import android.util.Log;
...
public class MyActivity extends Activity {
private static final String TAG = MyActivity.class.getSimpleName();
...
@Override
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
Log.d(TAG, "onCreate() Restoring previous state");
/* restore state */
} else {
Log.d(TAG, "onCreate() No saved state available");
/* initialize app */
}
}
}
android {
buildTypes {
customDebugType {
debuggable true
...
}
}
}

String uri = Uri.Builder()


.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(context.getPackageName()) // Look up the resources in the
application with its splits loaded
<manifest ... >
<application ... >
<activity android:name=".ExampleActivity" />
...
</application ... >
...
</manifest >

<activity android:name=".ExampleActivity"
android:icon="@drawable/app_icon">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>

// Create the text message with a string


Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
// Start the activity
startActivity(sendIntent);
<manifest>
<activity android:name="...."
android:permission=”com.google.socialapp.permission.SHARE_POST”

/>
.appendPath(resources.getResourceTypeName(resId))
.appendPath(String.format("%s:%s",
resources.getResourcePackageName(resId), // Look up the dynamic
resource in the split namespace.
resources.getResourceEntryName(resId)
))
.build().toString();

2.Create user input sections and screen navigation.


<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:layout_margin="5dp"
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="@string/empty"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#A4C639" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="23dp"
android:text="@string/input_lable"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#0099FF" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:background="#CCCCCC"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="20dp"
android:background="#0099FF"
android:text="@string/sub"
android:textColor="#FFFFFF" />
</RelativeLayout>
FrmActivity.java
package com.javapapers.android.form;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FrmActivity extends Activity {
Button mButton;
EditText mEdit;
TextView mText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frm);
mButton = (Button)findViewById(R.id.button1)
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mEdit = (EditText)findViewById(R.id.editText1);
mText = (TextView)findViewById(R.id.textView1);
mText.setText("Welcome "+mEdit.getText().toString()+"!");
} }); } }

Output :-
3.Testing user interface.
activity_main.xml
<RelativeLayout
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UI Animator Viewer"
android:id="@+id/textView"
android:textSize="25sp"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:textColor="#ff36ff15"
android:textIsSelectable="false"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button"
android:layout_marginTop="98dp"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true" />

</RelativeLayout>

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

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Button"
android:id="@+id/button2"
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Strings.xml.
<resources>
<string name="app_name">My Application</string>
</resources>
AndroidManifest.xml.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorialspoint.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>

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

</application>
</manifest>

MainActivity.java.
package com.tutorialspoint.myapplication;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {


Button b1;

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

b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in =new Intent(MainActivity.this,second.class);
startActivity(in);
}
});
}
}
second.java
package com.tutorialspoint.myapplication;

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

public class second extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Button b1=(Button)findViewById(R.id.button2);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(second.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}

4.Handling background task.


Xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="4dip" >
</ProgressBar>

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" >
</TextView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startProgress"
android:text="Start Progress" >
</Button>

</LinearLayout>
Main activity
package de.vogella.android.handler;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ProgressTestActivity extends Activity {


private ProgressBar progress;
private TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
text = (TextView) findViewById(R.id.textView1);

public void startProgress(View view) {


// do something long
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
doFakeWork();
progress.post(new Runnable() {
@Override
public void run() {
text.setText("Updating");
progress.setProgress(value);
}
});
}
}
};
new Thread(runnable).start();
}

// Simulating something timeconsuming


private void doFakeWork() {
SystemClock.sleep(5000);e.printStackTrace();
}

package de.vogella.android.asynctask;

// imports cut out for brevity

public class ReadWebpageAsyncTask extends Activity {


private TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.TextView01);
}
private class DownloadWebPageTask extends AsyncTask<String, Void,
String> {
@Override
protected String doInBackground(String... urls) {
// we use the OkHttp library from https://github.com/square/okhttp
OkHttpClient client = new OkHttpClient();
Request request =
new Request.Builder()
.url(urls[0])
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
}
return "Download failed";
}

@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}

// Triggered via a button in your layout


public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "https://www.vogella.com/index.html" });
}
}

<application android:icon="@drawable/icon"
android:label="@string/app_name"
android:name="MyApplicationClass">
<activity android:name=".ThreadsLifecycleActivity"
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>

5. Connection to internet.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="Check Internet Connection" />
</LinearLayout>
MainActivity.java
package com.tutlane.internetconnectionexample;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStatus = (Button)findViewById(R.id.btnCheck);
btnStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Check for Internet Connection
if (isConnected()) {
Toast.makeText(getApplicationContext(), "Internet Connected",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection",
Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean isConnected() {
boolean connected = false;
try {
ConnectivityManager cm =
(ConnectivityManager)getApplicationContext().getSystemService(Context.CON
NECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.internetconnectionexample">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

6. Handle Multiple tasks, notification pop up, Broadcast Receiver.


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.ownservice.local"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />


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

<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".ServiceConsumerActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>

<receiver android:name="MyScheduleReceiver" >


<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="MyStartServiceReceiver" >
</receiver>
</application>

</manifest>
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// assumes WordService is a registered service
Intent intent = new Intent(context, WordService.class);
context.startService(intent);
}
}
public static void sendNotification(Context caller, Class<?> activityToLaunch,
String title, String msg, int numberOfEvents,boolean sound, boolean flashLed,
boolean vibrate,int iconID) {
NotificationManager notifier = (NotificationManager)
caller.getSystemService(Context.NOTIFICATION_SERVICE);

final Notification notify = new Notification(iconID, "",


System.currentTimeMillis());

notify.icon = iconID;
notify.tickerText = title;
notify.when = System.currentTimeMillis();
notify.number = numberOfEvents;
notify.flags |= Notification.FLAG_AUTO_CANCEL;
if (sound) notify.defaults |= Notification.DEFAULT_SOUND;
if (flashLed) {
// add lights
notify.flags |= Notification.FLAG_SHOW_LIGHTS;
notify.ledARGB = Color.CYAN;
notify.ledOnMS = 500;
notify.ledOffMS = 500;
}

if (vibrate) {
notify.vibrate = new long[] {100, 200, 300};
}

Intent toLaunch = new Intent(caller, activityToLaunch);


toLaunch.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
toLaunch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intentBack = PendingIntent.getActivity(caller, number,
toLaunch, 0);

notify.setLatestEventInfo(caller, title, msg, intentBack);


notifier.notify(number, notify);
number = number+1;
}
7.Overview about SQLite database and its using in android.
package example.javatpoint.com.sqlitetutorial;

public class Contact {


int _id;
String _name;
String _phone_number;
public Contact(){ }
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}

public Contact(String name, String _phone_number){


this._name = name;
this._phone_number = _phone_number;
}
public int getID(){
return this._id;
}

public void setID(int id){


this._id = id;
}

public String getName(){


return this._name;
}
public void setName(String name){
this._name = name;
}

public String getPhoneNumber(){


return this._phone_number;
}

public void setPhoneNumber(String phone_number){


this._phone_number = phone_number;
}
}
package example.javatpoint.com.sqlitetutorial;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {


private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS
+ "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again


onCreate(db);
}

// code to add the new contact


void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
//2nd argument is String containing nullColumnHack
db.close(); // Closing database connection
}

// code to get the single contact


Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,


KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}

// code to get all contacts in a list view


public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list


if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}

// return contact list


return contactList;
}

// code to update the single contact


public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}

// Deleting single contact


public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}

}
File: MainActivity.java
package example.javatpoint.com.sqlitetutorial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.List;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);

// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "9100000000"));
db.addContact(new Contact("Srinivas", "9199999999"));
db.addContact(new Contact("Tommy", "9522222222"));
db.addContact(new Contact("Karthik", "9533333333"));

// Reading all contacts


Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();

for (Contact cn : contacts) {


String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
8. Storing data using SQLite and sorting data.
<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"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Enter Name"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/salary"
android:layout_width="match_parent"
android:inputType="numberDecimal"
android:hint="Enter Salary"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"><Button
android:id="@+id/save"
android:text="Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/refresh"
android:text="Refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/udate"
android:text="Update"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
Main activity
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


Button save, refresh;
EditText name, salary;
private ListView listView;

@Override
protected void onCreate(Bundle readdInstanceState) {
super.onCreate(readdInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper helper = new DatabaseHelper(this);
final ArrayList array_list = helper.getAllCotacts();
name = findViewById(R.id.name);
salary = findViewById(R.id.salary);
listView = findViewById(R.id.listView);
final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, array_list);
listView.setAdapter(arrayAdapter);
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
array_list.clear();
array_list.addAll(helper.getAllCotacts());
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
listView.refreshDrawableState();
}
});
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty() &&
!salary.getText().toString().isEmpty()) {
if (helper.insert(name.getText().toString(), salary.getText().toString()))
{
Toast.makeText(MainActivity.this, "Inserted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Inserted",
Toast.LENGTH_LONG).show();
}
} else {
name.setError("Enter NAME");
salary.setError("Enter Salary");
}
}
});
}
}

DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.IOException;
import java.util.ArrayList;

class DatabaseHelper extends SQLiteOpenHelper {


public static final String DATABASE_NAME = "salaryDatabase5";
public static final String CONTACTS_TABLE_NAME = "SalaryDetails";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,1);
}

@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(
"create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY,
name text,salary text,datetime default current_timestamp )"
);
} catch (SQLiteException e) {
try {
throw new IOException(e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

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

public boolean insert(String s, String s1) {


SQLiteDatabase db = this.getWritableDatabase();

ContentValues contentValues = new ContentValues();


contentValues.put("name", s);
contentValues.put("salary", s1);
db.replace(CONTACTS_TABLE_NAME, null, contentValues);
return true;
}

public ArrayList getAllCotacts() {


SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> array_list = new ArrayList<String>();
Cursor res = db.rawQuery( "select * from "+CONTACTS_TABLE_NAME+"
ORDER BY name DESC", null );
res.moveToFirst();

while(res.isAfterLast() == false) {
array_list.add(res.getString(res.getColumnIndex("name")));
res.moveToNext();
}
return array_list;
}

public boolean update(String s, String s1) {


SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("UPDATE "+CONTACTS_TABLE_NAME+" SET name = "+"'"+s+"',
"+ "salary = "+"'"+s1+"'");
return true;
}

public boolean delete() {


SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE from "+CONTACTS_TABLE_NAME);
return true;
}
}

9.Sharing data and loading data using loader.


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

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:indeterminate="true" />

</RelativeLayout>
public class MainActivity extends Activity implements OnClickListener {

myTask mytask = new myTask();


Button button1;
ProgressBar progressbar;

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

button1 = (Button) findViewById(R.id.button1);


progressbar = (ProgressBar) findViewById(R.id.progressBar);
button1.setOnClickListener(this);
}

@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;
}

@Override
public void onClick(View view) {
mytask.execute();
}

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


@Override
protected void onPreExecute() {
progressbar.setProgress(0);
progressbar.setMax(100);
int progressbarstatus = 0;
};

@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressbar.incrementProgressBy(10);
}
return "completed";
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);

@Override
protected void onProgressUpdate(String... values) {

super.onProgressUpdate(values);
}
}
}
public class YoutubeVideoMain extends Activity {

ListView videolist;

ArrayList<String> videoArrayList = new ArrayList<String>();

ArrayAdapter<String> videoadapter;
Context context;
String feedURL =
"https://gdata.youtube.com/feeds/api/users/twistedequations/uploads?v=2&
alt=jsonc&start-index=1&max-results=5";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.youtubelist);
videolist = (ListView) findViewById(R.id.videolist);

videoadapter = new ArrayAdapter<String>(this, R.layout.video_list_item,


videoArrayList);

videolist.setAdapter(videoadapter);
VideoListTask loadertask = new VideoListTask();
loadertask.execute();
}

private class VideoListTask extends AsyncTask<Void, String, Void> {

ProgressDialog dialogue;

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialogue.dismiss();

videoadapter.notifyDataSetChanged();
}

@Override
protected void onPreExecute() {
dialogue = new ProgressDialog(context);
dialogue.setTitle("Loading items..");
dialogue.show();
super.onPreExecute();

@Override
protected Void doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(feedURL);
try {
HttpResponse response = client.execute(getRequest);
StatusLine statusline = response.getStatusLine();
int statuscode = statusline.getStatusCode();

if (statuscode != 200) {

return null;
}

InputStream jsonStream = response.getEntity().getContent();

BufferedReader reader = new BufferedReader(


new InputStreamReader(jsonStream));

StringBuilder builder = new StringBuilder();


String line;

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

builder.append(line);

}
String jsonData = builder.toString();
JSONObject json = new JSONObject(jsonData);

JSONObject data = json.getJSONObject("data");

JSONArray items = data.getJSONArray("items");

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

JSONObject video = items.getJSONObject(i);

videoArrayList.add(video.getString("title"));

Log.i("YouJsonData:", jsonData);

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

return null;
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
lass YourCLassName extends AsyncTask<String, Integer, Void> {

private ProgressDialog pd = new ProgressDialog(Files.this);

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.setTitle("your message");

pd.show();

@Override
protected Void doInBackground(String... params) {
// YOUR PIECE OF CODE

return null;
}

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);

pd.setMessage("Task Completed .. whatever");

@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}

10. Testing the app and Publish.


public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

view.findViewById(R.id.random_button).setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
int currentCount =
Integer.parseInt(showCountTextView.getText().toString());
FirstFragmentDirections.ActionFirstFragmentToSecondFragment action =
FirstFragmentDirections.actionFirstFragmentToSecondFragment(currentCount)
;

NavHostFragment.findNavController(FirstFragment.this).navigate(action);
}
});

view.findViewById(R.id.toast_button).setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
Toast myToast = Toast.makeText(getActivity(), "Hello toast!",
Toast.LENGTH_SHORT);
myToast.show();
}
});

view.findViewById(R.id.count_button).setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
countMe(view);
}
});
}
import androidx.test.espresso.accessibility.AccessibilityChecks;

@Before
public void setUp() {
AccessibilityChecks.enable();
}
protected Void doInBackground(Void... params) {

HttpClient client = new DefaultHttpClient();


HttpGet getRequest = new HttpGet(feedURL);
try {
HttpResponse response = client.execute(getRequest);
StatusLine statusline = response.getStatusLine();
int statuscode = statusline.getStatusCode();

if (statuscode != 200) {
return null;
}

InputStream jsonStream = response.getEntity().getContent();

BufferedReader reader = new BufferedReader(


new InputStreamReader(jsonStream));

StringBuilder builder = new StringBuilder();


String line;

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

builder.append(line);

}
String jsonData = builder.toString();

JSONObject json = new JSONObject(jsonData);

JSONObject data = json.getJSONObject("data");


JSONArray items = data.getJSONArray("items");

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

JSONObject video = items.getJSONObject(i);

videoArrayList.add(video.getString("title"));

Log.i("YouJsonData:", jsonData);

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
@Test
@SdkSuppress(maxSdkVersion = 27)
public void testButtonClickOnOreoAndLower() {
// ...
}

@Test
@SdkSuppress(minSdkVersion = 28)
public void testButtonClickOnPieAndHigher() {
// ...
}

You might also like