Android Development Essentials: Telephony, Storage, and XML Manipulation

Initiating Phone Calls

To implement a dialer functionality, an Intent with the ACTION_CALL action is required. This necessitates the CALL_PHONE permission in the AndroidManifest.xml file.

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

The following implementation demonstrates how to extract a phone number from an EditText, validate it, and initiate the call.

public class DialerActivity extends AppCompatActivity {

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

    public void initiateCall(View view) {
        EditText phoneInput = findViewById(R.id.et_phone_number);
        String number = phoneInput.getText().toString().trim();

        if (TextUtils.isEmpty(number)) {
            Toast.makeText(this, "Number cannot be empty", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + number));
        startActivity(callIntent);
    }
}

Internal Storage Operations

Internal storage provides a private space for application data. Files saved here are private to the application and are removed when the app is uninstalled.

public class InternalStorageManager {

    private static final String FILE_NAME = "user_credentials.txt";

    public static boolean saveCredentials(Context context, String user, String pass) {
        try (FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE)) {
            String data = user + ":" + pass;
            fos.write(data.getBytes());
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static Map<String, String> loadCredentials(Context context) {
        try (FileInputStream fis = context.openFileInput(FILE_NAME)) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            String line = reader.readLine();
            if (line != null) {
                String[] parts = line.split(":");
                Map<String, String> creds = new HashMap<>();
                creds.put("username", parts[0]);
                creds.put("password", parts[1]);
                return creds;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

External Storage Access

Interacting with external storage (SD card) requires specific permissions. It is crucial to check the storage state before attempting read or write operations.

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

The following snippet checks storage availability and retrieves space statistics.

public void checkExternalStorage() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File sdDir = Environment.getExternalStorageDirectory();
        long totalSpace = sdDir.getTotalSpace();
        long usableSpace = sdDir.getUsableSpace();
        
        String total = Formatter.formatFileSize(this, totalSpace);
        String free = Formatter.formatFileSize(this, usableSpace);
        
        Log.d("Storage", "Total: " + total + ", Free: " + free);
    } else {
        Toast.makeText(this, "SD Card unavailable", Toast.LENGTH_SHORT).show();
    }
}

SharedPreferences for Key-Value Storage

SharedPreferences allows saving primitive data types in key-value pairs. It is ideal for storing user preferences or session tokens.

Saving Data:

SharedPreferences preferences = getSharedPreferences("app_settings", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("key_username", username);
editor.putString("key_password", password);
editor.apply();

Retrieving Data:

SharedPreferences preferences = getSharedPreferences("app_settings", MODE_PRIVATE);
String savedUser = preferences.getString("key_username", "");
String savedPass = preferences.getString("key_password", "");

Generating XML with XmlSerializer

Android provides XmlSerializer to write XML structures efficiently. This example creates a configuration XML file on external storage.

public void createConfigXml() {
    try {
        XmlSerializer serializer = Xml.newSerializer();
        File file = new File(Environment.getExternalStorageDirectory(), "config.xml");
        FileOutputStream fos = new FileOutputStream(file);
        
        serializer.setOutput(fos, "UTF-8");
        serializer.startDocument("UTF-8", true);
        
        serializer.startTag(null, "config");
        serializer.attribute(null, "version", "1.0");
        
        serializer.startTag(null, "setting");
        serializer.text("Enabled");
        serializer.endTag(null, "setting");
        
        serializer.endTag(null, "config");
        serializer.endDocument();
        
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Parsing XML with XmlPullParser

The XmlPullParser is an efficient way to parse XML documents. It uses an event-driven model to iterate through the XML structure. Assume an XML file named students.xml is located in the assets folder.

Parser Utility:

public class StudentXmlParser {

    public static List<Student> parse(InputStream inputStream) throws XmlPullParserException, IOException {
        List<Student> students = null;
        Student currentStudent = null;
        
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(inputStream, "UTF-8");
        
        int eventType = parser.getEventType();
        
        while (eventType != XmlPullParser.END_DOCUMENT) {
            String tagName = parser.getName();
            
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    students = new ArrayList<>();
                    break;
                case XmlPullParser.START_TAG:
                    if ("student".equals(tagName)) {
                        currentStudent = new Student();
                        currentStudent.setId(Integer.parseInt(parser.getAttributeValue(0)));
                    } else if (currentStudent != null) {
                        if ("name".equals(tagName)) {
                            currentStudent.setName(parser.nextText());
                        } else if ("grade".equals(tagName)) {
                            currentStudent.setGrade(parser.nextText());
                        }
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if ("student".equals(tagName) && currentStudent != null) {
                        students.add(currentStudent);
                        currentStudent = null;
                    }
                    break;
            }
            eventType = parser.next();
        }
        return students;
    }
}

Activity Implementation:

public class StudentListActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_list);
        TextView displayView = findViewById(R.id.tv_display);
        
        try {
            InputStream is = getAssets().open("students.xml");
            List<Student> result = StudentXmlParser.parse(is);
            
            StringBuilder builder = new StringBuilder();
            for (Student s : result) {
                builder.append(s.toString()).append("\n");
            }
            displayView.setText(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Tags: Android java Storage XML Telephony

Posted on Thu, 01 Oct 2026 16:13:39 +0000 by kritro