By GokiSoft.com| 19:34 07/12/2020|
Android

[Video] Hướng dẫn tạo Food App bằng ListView + BaseAdapter - Lập trình android


Full Source Code - Food Application - Lap Trinh Android

#AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gokisoft.c1812l">

    <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" />
        <activity android:name=".LoginActivity"></activity>
        <activity android:name=".RegisterActivity" />
        <activity android:name=".FruitActivity">
        </activity>
        <activity android:name=".FoodActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>


#FoodAdapter.java


package com.gokisoft.c1812l.adapters;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.gokisoft.c1812l.R;
import com.gokisoft.c1812l.models.Food;

import java.util.List;

/**
 * Created by Diep.Tran on 11/27/20.
 */

public class FoodAdapter extends BaseAdapter {
    Activity activity;
    List<Food> dataList;

    public FoodAdapter(Activity activity, List<Food> dataList) {
        this.activity = activity;
        this.dataList = dataList;
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public Object getItem(int i) {
        return dataList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        LayoutInflater inflater = activity.getLayoutInflater();
        view = inflater.inflate(R.layout.item_food, null);

        ImageView thumbnail = view.findViewById(R.id.ifo_thumbnail);
        TextView title = view.findViewById(R.id.ifo_title);
        TextView content = view.findViewById(R.id.ifo_content);
        TextView price = view.findViewById(R.id.ifo_price);

        Food food = dataList.get(position);

        thumbnail.setImageResource(food.getResId());
        title.setText(food.getTitle());
        content.setText(food.getContent());
        price.setText(String.valueOf(food.getPrice()));

        return view;
    }
}


#Food.java


package com.gokisoft.c1812l.models;

/**
 * Created by Diep.Tran on 11/27/20.
 */

public class Food {
    int resId;
    String title, content;
    float price;

    public Food(int resId) {
        this.resId = resId;
    }

    public Food(int resId, String title, String content, float price) {
        this.resId = resId;
        this.title = title;
        this.content = content;
        this.price = price;
    }

    public int getResId() {
        return resId;
    }

    public void setResId(int resId) {
        this.resId = resId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }
}


#FoodActivity.java


package com.gokisoft.c1812l;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import com.gokisoft.c1812l.adapters.FoodAdapter;
import com.gokisoft.c1812l.models.Food;

import java.util.ArrayList;
import java.util.List;

public class FoodActivity extends AppCompatActivity {
    ListView listView;
    List<Food> dataList = new ArrayList<>();
    FoodAdapter foodAdapter;
    int currentIndex = -1;

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

        listView = findViewById(R.id.afo_listview);

        //fake data
        dataList.add(new Food(R.drawable.food01, "Pizza 01", "Ok Ngon 01", 100000));
        dataList.add(new Food(R.drawable.food02, "Pizza 02", "Ok Ngon 02", 120000));
        dataList.add(new Food(R.drawable.food03, "Pizza 03", "Ok Ngon 03", 160000));

        //create adapter
        foodAdapter = new FoodAdapter(this, dataList);
        listView.setAdapter(foodAdapter);

        //dang ky context menu
        registerForContextMenu(listView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_content, menu);

        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int index = info.position;

        switch (item.getItemId()) {
            case R.id.menu_edit_item:
                //Them item moi
                this.currentIndex = index;
                showDialogAdd();
                return true;
            case R.id.menu_delete_item:
                dataList.remove(index);
                foodAdapter.notifyDataSetChanged();

                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_add_new_item:
                //Them item moi
                showDialogAdd();
                return true;
            case R.id.menu_exit:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void showDialogAdd() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_food, null);

        final EditText edTitle = view.findViewById(R.id.df_title);
        final EditText edContent = view.findViewById(R.id.df_content);
        final EditText edPrice = view.findViewById(R.id.df_price);
        if(currentIndex >= 0) {
            edTitle.setText(dataList.get(currentIndex).getTitle());
            edContent.setText(dataList.get(currentIndex).getContent());
            edPrice.setText(String.valueOf(dataList.get(currentIndex).getPrice()));
        }

        builder.setView(view);
        builder.setTitle("Add/Update Item")
                .setPositiveButton("Save Item", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String title = edTitle.getText().toString();
                String content = edContent.getText().toString();
                float price = Float.parseFloat(edPrice.getText().toString());

                if(currentIndex >= 0) {
                    dataList.get(currentIndex).setTitle(title);
                    dataList.get(currentIndex).setContent(content);
                    dataList.get(currentIndex).setPrice(price);
                    currentIndex = -1;
                } else {
                    Food food = new Food(R.drawable.food01, title, content, price);
                    dataList.add(food);
                }


                foodAdapter.notifyDataSetChanged();
            }
        }).setNegativeButton("Cencel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        builder.show();
    }
}


#menu.xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_add_new_item"
        android:title="Add new item"/>
    <item android:id="@+id/menu_exit"
        android:title="Exit" />
</menu>


#menu_content.xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_edit_item"
        android:title="Edit item"/>
    <item android:id="@+id/menu_delete_item"
        android:title="Delete item" />
</menu>


#item_food.xml


<?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"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/ifo_thumbnail"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_weight="1"
        android:src="@drawable/food01" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/ifo_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <TextView
            android:id="@+id/ifo_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <TextView
            android:id="@+id/ifo_price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>
</LinearLayout>


#dialog_food.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/df_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <EditText
        android:id="@+id/df_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textMultiLine" />

    <EditText
        android:id="@+id/df_price"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal" />
</LinearLayout>


#activity_food.xml


<?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="5dp"
    tools:context="com.gokisoft.c1812l.FoodActivity">

    <ListView
        android:id="@+id/afo_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>


Tags:



Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

TRẦN VĂN ĐIỆP [Teacher]
TRẦN VĂN ĐIỆP

2020-11-30 12:58:57



package com.gokisoft.c1812l;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import com.gokisoft.c1812l.adapters.FoodAdapter;
import com.gokisoft.c1812l.models.Food;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class FoodActivity extends AppCompatActivity {
    ListView listView;
    List<Food> dataList = new ArrayList<>();
    FoodAdapter foodAdapter;
    int currentIndex = -1;

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

        listView = findViewById(R.id.afo_listview);

//        //fake data
//        dataList.add(new Food(R.drawable.food01, "Pizza 01", "Ok Ngon 01", 100000));
//        dataList.add(new Food(R.drawable.food02, "Pizza 02", "Ok Ngon 02", 120000));
//        dataList.add(new Food(R.drawable.food03, "Pizza 03", "Ok Ngon 03", 160000));
//        readFile();
        readSharedPreferences();

        //create adapter
        foodAdapter = new FoodAdapter(this, dataList);
        listView.setAdapter(foodAdapter);

        //dang ky context menu
        registerForContextMenu(listView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_content, menu);

        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int index = info.position;

        switch (item.getItemId()) {
            case R.id.menu_edit_item:
                //Them item moi
                this.currentIndex = index;
                showDialogAdd();
                return true;
            case R.id.menu_delete_item:
                dataList.remove(index);
                foodAdapter.notifyDataSetChanged();

                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_add_new_item:
                //Them item moi
                showDialogAdd();
                return true;
            case R.id.menu_exit:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void readFile() {
        //code save File o day
        ObjectInputStream ois = null;
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(getFileStreamPath("food.dat"));
            ois = new ObjectInputStream(fis);

            //save file
            dataList = (List<Food>) ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void saveFile() {
        //code save File o day
        ObjectOutputStream oos = null;
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(getFileStreamPath("food.dat"));
            oos = new ObjectOutputStream(fos);

            //save file
            oos.writeObject(dataList);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void saveSharedPreferences() {
        //Save dataList => Object Array => convert Object Array => String (json string)
        //Su dung thu vien gson => convert object/array => json string va nguoc lai
        String json = new Gson().toJson(dataList);
        //save json to SharedPreferences
        SharedPreferences sharedPreferences = getSharedPreferences("C1808G", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        //save
        editor.putString("dataList", json);

        editor.commit();
    }

    private void readSharedPreferences() {
        SharedPreferences sharedPreferences = getSharedPreferences("C1808G", MODE_PRIVATE);

        String json = sharedPreferences.getString("dataList", "[]");

        //convert json string => object array
        Gson gson = new Gson();
        dataList = gson.fromJson(json, new TypeToken<List<Food>>(){}.getType());

        if(dataList == null) {
            dataList = new ArrayList<>();
        }
    }

    private void showDialogAdd() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_food, null);

        final EditText edTitle = view.findViewById(R.id.df_title);
        final EditText edContent = view.findViewById(R.id.df_content);
        final EditText edPrice = view.findViewById(R.id.df_price);
        if(currentIndex >= 0) {
            edTitle.setText(dataList.get(currentIndex).getTitle());
            edContent.setText(dataList.get(currentIndex).getContent());
            edPrice.setText(String.valueOf(dataList.get(currentIndex).getPrice()));
        }

        builder.setView(view);
        builder.setTitle("Add/Update Item")
                .setPositiveButton("Save Item", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String title = edTitle.getText().toString();
                String content = edContent.getText().toString();
                float price = Float.parseFloat(edPrice.getText().toString());

                if(currentIndex >= 0) {
                    dataList.get(currentIndex).setTitle(title);
                    dataList.get(currentIndex).setContent(content);
                    dataList.get(currentIndex).setPrice(price);
                    currentIndex = -1;
                } else {
                    Food food = new Food(R.drawable.food01, title, content, price);
                    dataList.add(food);
                }

//                saveFile();
                saveSharedPreferences();

                foodAdapter.notifyDataSetChanged();
            }
        }).setNegativeButton("Cencel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        builder.show();
    }
}



Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó