0% found this document useful (0 votes)
46 views10 pages

Mad Unit 5

Uploaded by

sarathreddiwork
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views10 pages

Mad Unit 5

Uploaded by

sarathreddiwork
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Setting up a "Drag and Draw" project in Android requires creating a custom view where users can draw by

dragging their fingers across the screen. Here's a step-by-step guide to set up the project, create a custom
view, and handle touch events for drawing.
1. Setting Up the Project
1. Create a New Project in Android Studio.
2. Add a Custom View class to handle drawing.
3. Set up the Layout to use the custom view.
For this example, we’ll assume the main activity XML layout (activity_main.xml) includes only the custom
view that will handle the drawing.
2. Creating a Custom View
In Android, we create a custom view by extending the View class and overriding methods to handle
drawing and touch events.
Step 1: Create the Custom View Class
Create a new Java class, DragAndDrawView, that extends View.
public class DragAndDrawView extends View {

private Path path = new Path(); // Stores the path to be drawn


private Paint paint = new Paint();

public DragAndDrawView(Context context, AttributeSet attrs) {


super(context, attrs);

// Initialize paint properties


paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(8f);
paint.setAntiAlias(true);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the path as the user moves their finger
canvas.drawPath(path, paint);
}
}
Here's the DragAndDrawView code and the corresponding XML layout in Java.
1. DragAndDrawView Java Code
public class DragAndDrawView extends View {

private Path path = new Path(); // Stores the path to be drawn


private Paint paint = new Paint();

public DragAndDrawView(Context context, AttributeSet attrs) {


super(context, attrs);

// Initialize paint properties


paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(8f);
paint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the path as the user moves their finger
canvas.drawPath(path, paint);
}
}
2. XML Layout (activity_main.xml)
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<com.example.draganddraw.DragAndDrawView
android:id="@+id/dragAndDrawView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
3. Handling Touch Events
Now, let’s add touch handling to enable dragging and drawing.
Step 1: Override onTouchEvent
In the DragAndDrawView class, override the onTouchEvent method to handle drawing as the user touches
and drags.
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Start a new path
path.moveTo(x, y);
return true;

case MotionEvent.ACTION_MOVE:
// Draw a line to the new position
path.lineTo(x, y);
break;

case MotionEvent.ACTION_UP:
// Path is complete; additional handling could go here
break;
}

// Request the view to redraw


invalidate();
return true;
}
working with text files and working with data tables using SQLite
In Android, text files and SQLite databases are common choices for data storage.

1. Working with Text Files


Text files are suitable for storing small, structured or unstructured data such as logs, configuration details.
 Storage Location: You can store files in internal storage (private to the app) or external
storage (accessible by other apps and users).
 File Access: Use FileOutputStream and FileInputStream to write to and read from files.
Writing to a Text File in Internal Storage
String filename = "myfile.txt";
String fileContents = "Hello, World!";
try (FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.getBytes());
fos.flush(); // Ensure all data is written
} catch (IOException e) {
e.printStackTrace();
}
Reading from a Text File in Internal Storage
String filename = "myfile.txt";
StringBuilder fileContent = new StringBuilder();
try (FileInputStream fis = openFileInput(filename)) {
int character;
while ((character = fis.read()) != -1) {
fileContent.append((char) character);
}
} catch (IOException e) {
e.printStackTrace();
}
String fileData = fileContent.toString(); // Contains the content of the file
Deleting a File
boolean deleted = deleteFile("myfile.txt");

2. Working with Data Tables using SQLite


SQLite is an embedded database in Android, well-suited for apps that require structured data storage
with querying capabilities. It is ideal for relational data and allows SQL operations.
Setting up an SQLite Database
You can manage an SQLite database in Android with SQLite Open Helper, which provides methods for
database creation and version management.
1. Create a Database Helper Class:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabaseHelper extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "MyDatabase.db";
private static final int DATABASE_VERSION = 1;
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE Users (id INTEGER PRIMARY KEY AUTOINCREMENT, name
TEXT, age INTEGER)";
db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Users");
onCreate(db);
}
}
Inserting Data:
public void insertUser(String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);

db.insert("Users", null, values);


db.close();
}
Querying Data
public List<User> getAllUsers() {
List<User> userList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Users", null);

if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
int age = cursor.getInt(cursor.getColumnIndexOrThrow("age"));
userList.add(new User(id, name, age));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return userList;
}
Updating Data:
public void updateUser(int id, String newName, int newAge) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", newName);
values.put("age", newAge);

db.update("Users", values, "id=?", new String[]{String.valueOf(id)});


db.close();
}
Deleting Data:
public void deleteUser(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete("Users", "id=?", new String[]{String.valueOf(id)});
db.close();
}
XML pull parser, XML resource parser
In Android, parsing XML data is often necessary when dealing with
configurations or data feeds. Android provides several options for XML
parsing, including XML Pull Parser and XML Resource Parser. Here’s an
overview of each and how they’re commonly used.
1. XML Pull Parser
Overview
The XML Pull Parser is an efficient, streaming XML parser included with
Android. It’s ideal for parsing large XML files because it reads the file
incrementally, event by event, rather than loading the entire document into
memory.
How XML Pull Parser Works
The Pull Parser processes XML by generating events such as:
 START_DOCUMENT: Beginning of the document.
 END_DOCUMENT: End of the document.
 START_TAG: Start of an XML tag.
 END_TAG: End of an XML tag.
 TEXT: Text content between tags.
You can use these events to process XML data as you go through it, making
it memory-efficient.
Example: Parsing XML with XML Pull Parser
Let's say we have an XML file called students.xml:
<students>
<student>
<name>John Doe</name>
<age>20</age>
</student>
<student>
<name>Jane Smith</name>
<age>22</age>
</student>
</students>
Here’s how to parse it using XmlPullParser:
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.InputStream;

public List<String> parseStudentsXml(InputStream inputStream) {


List<String> students = new ArrayList<>();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(inputStream, null);

int eventType = parser.getEventType();


String name = null;
String text = null;

while (eventType != XmlPullParser.END_DOCUMENT) {


switch (eventType) {
case XmlPullParser.START_TAG:
name = parser.getName();
break;

case XmlPullParser.TEXT:
text = parser.getText();
break;

case XmlPullParser.END_TAG:
if (name.equals("name")) {
students.add("Name: " + text);
} else if (name.equals("age")) {
students.set(students.size() - 1, students.get(students.size() -
1) + ", Age: " + text);
}
name = null;
break;
}
eventType = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
}

return students;
}
2. XML Resource Parser
Overview
The XML Resource Parser is similar to the Pull Parser but is specifically
used for Android resource XML files, such as layout files (.xml), menu XMLs,
and drawable XMLs. It extends XmlPullParser and provides additional
methods for accessing Android-specific resources.
Use Case for XML Resource Parser
The XML Resource Parser is commonly used when accessing XML resources
stored in the res directory, such as res/xml or res/layout.
Example: Using XML Resource Parser for Resources
Suppose we have an XML file res/xml/students.xml:
<students>
<student>
<name>John Doe</name>
<age>20</age>
</student>
<student>
<name>Jane Smith</name>
<age>22</age>
</student>
</students>
Here's how to parse this using XmlResourceParser in an Activity or Context:
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

List<String> students = parseStudentsXml();


// Display or use the parsed student list
}

private List<String> parseStudentsXml() {


List<String> students = new ArrayList<>();
XmlResourceParser parser = getResources().getXml(R.xml.students);

try {
int eventType = parser.getEventType();
String name = null;
String text = null;

while (eventType != XmlPullParser.END_DOCUMENT) {


switch (eventType) {
case XmlPullParser.START_TAG:
name = parser.getName();
break;

case XmlPullParser.TEXT:
text = parser.getText();
break;

case XmlPullParser.END_TAG:
if ("name".equals(name)) {
students.add("Name: " + text);
} else if ("age".equals(name)) {
students.set(students.size() - 1, students.get(students.size() -
1) + ", Age: " + text);
}
name = null;
break;
}
eventType = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
parser.close();
}

return students;
}
}
XML Resource Parser vs. XML Pull Parser
Feature XML Pull Parser XML Resource Parser
General XML parsing (from Parsing Android-specific
Use Case
file or network) resources in res/xml
Android Not specifically integrated Extends XmlPullParser with
Integration with Android resources Android resource support
Pre-defined XML resources in
Typical Usage External XML data feeds
Android apps
Closing No specific close required close() must be called

You might also like