dipTech / AndroidDev

code path android dev
Other
0 stars 0 forks source link

Android Bootcamp Exercise ToDoApp #2

Open dipankar14 opened 10 years ago

dipankar14 commented 10 years ago

Submitting one activity with AlertDialog for edit feature, will try to submit the other approach using CodePath cliffnotes (in couple of days).

@nesquena and @timothy1ee

1 2 3 4

deletedlastitem

package com.example.todoapp;

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

import org.apache.commons.io.FileUtils;

import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView;

public class ToDoActivity extends Activity {

final private String filename = "todo.txt";
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter;
private ListView lvItems;
EditText etNewItem;

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

private void initialize() {
    etNewItem = (EditText)findViewById(R.id.etNewItem);
    lvItems = (ListView) findViewById(R.id.lvItems);
    readItems();
    todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems);
    lvItems.setAdapter(todoAdapter);
    setupListViewListener();        
}

private void setupListViewListener() {
    lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
            todoItems.remove(pos);
            todoAdapter.notifyDataSetChanged();
            writeItems();
            return true;
        }

    });

    lvItems.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> adapter, final View item, int pos, long id) {
            editAlert(item, pos);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.to_do, menu);
    return true;
}

public void onAddedItem(View v) {
    String itemText = etNewItem.getText().toString();
    if ((itemText == null) || (itemText.trim().length() == 0)) {
        etNewItem.setText("");
        return;
    }
    todoAdapter.add(itemText);
    writeItems();
    etNewItem.setText("");
}

private void readItems() {
    File filesDir = getFilesDir();
    File todoFile = new File(filesDir, filename);
    try {
        todoItems = new ArrayList<String>(FileUtils.readLines(todoFile));
    }
    catch (IOException ex) {
        todoItems = new ArrayList<String>();
        ex.printStackTrace();
    }
}

private void writeItems() {
    File filesDir = getFilesDir();
    File todoFile = new File(filesDir, filename);
    try {
        FileUtils.writeLines(todoFile, todoItems);
    }
    catch (IOException ex) {
        ex.printStackTrace();
    }
}

private void editAlert(View view, final int pos) {
    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ToDoActivity.this);

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    input.setText(todoItems.get(pos));
    alertDialogBuilder.setTitle(R.string.edit_task);
    alertDialogBuilder.setMessage(R.string.edit_msg);
    alertDialogBuilder.setView(input);

    alertDialogBuilder.setPositiveButton(R.string.save,
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    String value = input.getText().toString();
                    if ((value == null) || (value.trim().length() == 0)) {
                        input.setText("");
                        return;
                    }
                    todoItems.set(pos, value);
                    todoAdapter.notifyDataSetChanged();
                    writeItems();
                    input.setText("");
                }
            });

    AlertDialog alertDialog = alertDialogBuilder.create();
    // show alert
    alertDialog.show();
}

}

nesquena commented 10 years ago

Great, see if you can submit a version using 2 activities so you have a chance to play with how activity navigation works with intents. That was one of the key learnings of this pre-work.

Project looks good! This was intended in part to give you an introduction to the general rhythm of this course. The course is entirely project based with an app being assigned each week and then due the following week. Each project builds on the last to help each engineer to learn all practical Android development and best practices as quickly as possible. We also do a code review for each submitted project.

The next step is to schedule a short 10 minute phone conversation here. Navigate to May 14th - 16th and choose a slot. Let us know if none of those times work.

Once you select a slot, can you edit it with the best number to reach you at? Look forward to chatting!

P.S At the end of every bootcamp, we celebrate by hosting a public demo day with food/drinks and the best teams from iOS and Android present their projects competing for 10K of cash prizes. Would be great for you to RSVP and come by. It's on Monday, May 12th from 6:30-8:30pm at Yammer HQ.

dipankar14 commented 10 years ago

@nesquena and @timothy1ee

Enhancement by using second activity

appbase editactivity

Manifest File: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.todoapp" android:versionCode="1" android:versionName="1.0" >

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.todoapp.ToDoActivity"
        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="com.example.todoapp.EditItemActivity"
        android:label="@string/EditActivityTitle" >
    </activity>
</application>

New Activity Code package com.example.todoapp;

import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.EditText;

public class EditItemActivity extends Activity {

private EditText mtEditedText;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_item);
    setEditItem();
}

private void setEditItem() {
    Intent intent = getIntent();
    String item_value = intent.getStringExtra("itemValue");
    mtEditedText = (EditText)findViewById(R.id.mtTextToBeEdited);
    mtEditedText.setText(item_value);       
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.edit_item, menu);
    return true;
}

public void onSubmit(View v) {
    // Prepare data intent
    Intent data = new Intent();
    // Pass relevant data back as a result
    data.putExtra("itemValue", mtEditedText.getText().toString());
    // commented for now, now working
    // data.putExtra("position", data.getIntExtra("position", -1));
    // Activity finished ok, return the data
    setResult(RESULT_OK, data); // set result code and bundle data for response
    finish(); // closes the activity, pass data to parent
}

}

Changed Base Activity Code to support Intent package com.example.todoapp;

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

import org.apache.commons.io.FileUtils;

import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView;

public class ToDoActivity extends Activity {

final private String filename = "todo.txt";
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter;
private ListView lvItems;
EditText etNewItem;
final int REQUEST_CODE = 20;
private int currentPosition = 0;

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

private void initialize() {
    etNewItem = (EditText)findViewById(R.id.etNewItem);
    lvItems = (ListView) findViewById(R.id.lvItems);
    readItems();
    todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems);
    lvItems.setAdapter(todoAdapter);
    setupListViewListener();        
}

private void setupListViewListener() {
    lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
            todoItems.remove(pos);
            todoAdapter.notifyDataSetChanged();
            writeItems();
            return true;
        }

    });

    lvItems.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> adapter, final View item, int pos, long id) {
            Intent intent = new Intent(ToDoActivity.this, EditItemActivity.class);
            intent.putExtra("itemValue", todoItems.get(pos).toString());
            currentPosition = pos;
            // commented for now
            // intent.putExtra("position", pos);
            startActivityForResult(intent, REQUEST_CODE); // brings up the second activity
        }
    });
}

// ActivityOne.java, time to handle the result of the sub-activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // REQUEST_CODE is defined above
    if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
        // Extract name value from result extras
        String itemValue = data.getExtras().getString("itemValue");
        if (!(itemValue == null) || (itemValue.length() == 0)) {
            // commented for now, now working
            // int pos = data.getExtras().getInt("position");
            todoItems.set(currentPosition, itemValue);
            todoAdapter.notifyDataSetChanged();
            writeItems();
        }
    }
} 

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.to_do, menu);
    return true;
}

public void onAddedItem(View v) {
    String itemText = etNewItem.getText().toString();
    if ((itemText == null) || (itemText.trim().length() == 0)) {
        etNewItem.setText("");
        return;
    }
    todoAdapter.add(itemText);
    writeItems();
    etNewItem.setText("");
}

private void readItems() {
    File filesDir = getFilesDir();
    File todoFile = new File(filesDir, filename);
    try {
        todoItems = new ArrayList<String>(FileUtils.readLines(todoFile));
    }
    catch (IOException ex) {
        todoItems = new ArrayList<String>();
        ex.printStackTrace();
    }
}

private void writeItems() {
    File filesDir = getFilesDir();
    File todoFile = new File(filesDir, filename);
    try {
        FileUtils.writeLines(todoFile, todoItems);
    }
    catch (IOException ex) {
        ex.printStackTrace();
    }
}

}

nesquena commented 10 years ago

Looks good, thanks for submitting. In the future to submit alternate versions, might be better to create git branches rather than pasting in the code in full to the issue.