trouble passing object between Activities using intent parcelable extra - java

In my case, there is a listVIew in the first activity and by clicking on a listItem it redirects to another activity which allows to edit to edit details of the particular object item. once the selected item is edited in the second activity I want it to be updated in the first activity as well. I have used parcelable extra to pass data between two activities.
The first activity passes data to the second activity correctly but when it comes to updating the listView in the first activity using updated data in the second activity it throws a NullPointerException saying that the received object is null.
Please help me figure this out. thanks in advance.
Parcelable object class
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.RequiresApi;
import java.io.Serializable;
public class Movie implements Parcelable {
private String title;
private int releasedYear;
private String director;
private String cast;
private int rating;
private String review;
private boolean favourite;
public Movie(String title, int releasedYear, String director, String cast, int rating, String review) {
this.title = title;
this.releasedYear = releasedYear;
this.director = director;
this.cast = cast;
this.rating = rating;
this.review = review;
}
public Movie(String title, int releasedYear, String director, String cast, int rating, String review, boolean favourite) {
this.title = title;
this.releasedYear = releasedYear;
this.director = director;
this.cast = cast;
this.rating = rating;
this.review = review;
this.favourite = favourite;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getReleasedYear() {
return releasedYear;
}
public void setReleasedYear(int releasedYear) {
this.releasedYear = releasedYear;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getCast() {
return cast;
}
public void setCast(String cast) {
this.cast = cast;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public boolean isFavourite() {
return favourite;
}
public void setFavourite(boolean favourite) {
this.favourite = favourite;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeInt(this.releasedYear);
dest.writeString(this.director);
dest.writeString(this.cast);
dest.writeInt(this.rating);
dest.writeString(this.review);
dest.writeByte(this.favourite ? (byte) 1 : (byte) 0);
}
public void readFromParcel(Parcel source) {
this.title = source.readString();
this.releasedYear = source.readInt();
this.director = source.readString();
this.cast = source.readString();
this.rating = source.readInt();
this.review = source.readString();
this.favourite = source.readByte() != 0;
}
protected Movie(Parcel in) {
this.title = in.readString();
this.releasedYear = in.readInt();
this.director = in.readString();
this.cast = in.readString();
this.rating = in.readInt();
this.review = in.readString();
this.favourite = in.readByte() != 0;
}
public static final Creator<Movie> CREATOR = new Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel source) {
return new Movie(source);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
First activity
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.example.movietracker.database.CoreDatabase;
import java.util.ArrayList;
import java.util.List;
import static com.example.movietracker.database.Constants.TABLE_NAME;
import static com.example.movietracker.database.Constants.TITLE;
public class EditMovie extends AppCompatActivity {
private final int REQ_COE = 1;
CoreDatabase database;
List<Movie> movies;
Movie movieReturn;
RelativeLayout layout;
ListView listView;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_COE) {
if (resultCode == RESULT_OK) {
movieReturn = getIntent().getParcelableExtra("movieReturn");
movies.add(movieReturn);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_movie);
layout = findViewById(R.id.edit_relative_layout);
listView = findViewById(R.id.edit_listView);
movies = new ArrayList<>();
database = new CoreDatabase(this);
String query = "select * from "+ TABLE_NAME + " order by "+ TITLE + " ASC";
Cursor cursor = database.getData(query);
retrieveData(cursor);
System.out.println(movies.size());
MovieArrayAdapter adapter = new MovieArrayAdapter(this, movies);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EditMovie.this, EditMovieItemView.class);
intent.putExtra("movie", movies.get(position));
startActivityForResult(intent, 1);
movies.remove(position);
adapter.notifyDataSetChanged();
System.out.println(movies.size());
}
});
}
public void retrieveData(Cursor cursor){
while (cursor.moveToNext()) {
String title = cursor.getString(1);
int year = cursor.getInt(2);
String director = cursor.getString(3);
String cast = cursor.getString(4);
int rating = cursor.getInt(5);
String review = cursor.getString(6);
boolean favourite = cursor.getInt(7) > 0;
movies.add(new Movie(title, year, director, cast, rating, review, favourite));
}
}
}
Second Activity
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.widget.CheckBox;
import android.widget.NumberPicker;
import android.widget.RatingBar;
import android.widget.Toast;
import com.example.movietracker.database.CoreDatabase;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.List;
public class EditMovieItemView extends AppCompatActivity {
CoreDatabase database;
Movie movie;
String pickedDate, defaultTitle;
String updatedTitle, updatedDirector, updatedCast, updatedReview;
int updatedYear, updatedRating;
CheckBox favourite;
TextInputLayout title, year, director, cast, review;
NumberPicker yearPicker;
RatingBar rating1, rating2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_movie_item_view);
database = new CoreDatabase(this);
favourite = findViewById(R.id.edit_fav_checkbox);
title = findViewById(R.id.edit_movie_title);
year = findViewById(R.id.edit_movie_year);
year.getEditText().setFilters(new InputFilter[]{new MinMaxFilter(1895, 2021)});
director = findViewById(R.id.edit_movie_director);
cast = findViewById(R.id.edit_movie_cast);
rating1 = findViewById(R.id.edit_ratingBar1);
rating2 = findViewById(R.id.edit_ratingBar2);
review = findViewById(R.id.edit_movie_review);
yearPicker = findViewById(R.id.edit_year_picker);
yearPicker.setMinValue(1895);
yearPicker.setMaxValue(2021);
yearPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
pickedDate = String.valueOf(picker.getValue());
year.getEditText().setText(pickedDate);
}
});
if (getIntent().getExtras() != null){
movie = getIntent().getParcelableExtra("movie");
}
title.getEditText().setText(movie.getTitle());
year.getEditText().setText(String.valueOf(movie.getReleasedYear()));
director.getEditText().setText(movie.getDirector());
cast.getEditText().setText(movie.getCast());
review.getEditText().setText(movie.getReview());
if (movie.getRating() <= 5){
rating1.setRating(movie.getRating());
rating2.setRating(0);
} else {
rating1.setRating(5);
rating2.setRating(movie.getRating() - 5);
}
favourite.setChecked(movie.isFavourite());
defaultTitle = title.getEditText().getText().toString();
}
public void updateMovie(View view){
updatedTitle = title.getEditText().getText().toString();
updatedYear = Integer.parseInt(year.getEditText().getText().toString());
updatedDirector = director.getEditText().getText().toString();
updatedCast = cast.getEditText().getText().toString();
updatedReview = review.getEditText().getText().toString();
updatedRating = (int) (rating1.getRating() + rating2.getRating());
database.updateAllData(updatedTitle, updatedYear, updatedDirector, updatedCast, updatedRating, updatedReview, favourite.isChecked(), defaultTitle);
Toast.makeText(getApplicationContext(), "Successfully updated!", Toast.LENGTH_SHORT).show();
movie.setTitle(updatedTitle);
movie.setReleasedYear(updatedYear);
movie.setDirector(updatedDirector);
movie.setCast(updatedCast);
movie.setRating(updatedRating);
movie.setReview(updatedReview);
movie.setFavourite(favourite.isChecked());
Intent returnIntent = new Intent();
returnIntent.putExtra("movieReturn", movie);
setResult(RESULT_OK, returnIntent);
finish();
}
}

Related

Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference at com.example.newsapp.MainActivity$1.onResponse

I have this android News app code from a YouTube video GeeksForGeeks.
Wrote the same code but getting this error:
Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference at com.example.newsapp.MainActivity$1.onResponse
Please help me to solve this error.
Here is the code:
MainActivity.java
package com.example.newsapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity implements CategoryRVAdapter.CategorClickInterface{
//3cd3cc2c4be045caa48e900fc41032b1
private RecyclerView newsRV,categoryRV;
private ProgressBar loadingPB;
private ArrayList<Articles> articlesArrayList;
private ArrayList<CategoryRVModal> categoryRVModalArrayList;
private CategoryRVAdapter categoryRVAdapter;
private NewsRVAdapter newsRVAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newsRV = findViewById(R.id.idRVNews);
categoryRV = findViewById(R.id.idRVCategories);
loadingPB = findViewById(R.id.idPBLoading);
articlesArrayList = new ArrayList<>();
categoryRVModalArrayList = new ArrayList<>();
newsRVAdapter = new NewsRVAdapter(articlesArrayList,this);
categoryRVAdapter = new CategoryRVAdapter(categoryRVModalArrayList,this,this::onCategoryClick);
newsRV.setLayoutManager(new LinearLayoutManager(this));
newsRV.setAdapter(newsRVAdapter);
categoryRV.setAdapter(categoryRVAdapter);
getCategories();
getNews("All");
newsRVAdapter.notifyDataSetChanged();
}
private void getCategories() {
categoryRVModalArrayList.add(new CategoryRVModal("All","https://plus.unsplash.com/premium_photo-1665311515438-a8e9c0eda3d3?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTl8fG91dGRvb3J8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60"));
categoryRVModalArrayList.add(new CategoryRVModal("Technology","https://images.unsplash.com/photo-1488590528505-98d2b5aba04b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8dGVjaG5vbG9neXxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60"));
categoryRVModalArrayList.add(new CategoryRVModal("Science","https://plus.unsplash.com/premium_photo-1661284886645-1e21653e252a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTN8fHNjaWVuY2V8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60"));
categoryRVModalArrayList.add(new CategoryRVModal("Sports","https://images.unsplash.com/photo-1517649763962-0c623066013b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fHNwb3J0fGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60"));
categoryRVModalArrayList.add(new CategoryRVModal("General","https://images.unsplash.com/photo-1670516537787-22e2d8de641f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyMnx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60"));
categoryRVModalArrayList.add(new CategoryRVModal("Business","https://images.unsplash.com/photo-1460925895917-afdab827c52f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NDB8fGJ1c2luZXNzfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60"));
categoryRVModalArrayList.add(new CategoryRVModal("Entertainment","https://images.unsplash.com/photo-1603190287605-e6ade32fa852?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8ZW50ZXJ0YWlubWVudHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60"));
categoryRVModalArrayList.add(new CategoryRVModal("Health","https://images.unsplash.com/photo-1535914254981-b5012eebbd15?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTh8fGhlYWx0aHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60"));
categoryRVAdapter.notifyDataSetChanged();
}
private void getNews(String category){
loadingPB.setVisibility(View.VISIBLE);
articlesArrayList.clear();
String categoryURL = "https://newsapi.org/v2/top-headlines/sources?category=" + category + "&apiKey=3cd3cc2c4be045caa48e900fc41032b1";
String url = "https://newsapi.org/v2/top-headlines?country=in&excludeDomains=stackoverflow.com&shortBy=publishedAt&language=en&apiKey=3cd3cc2c4be045caa48e900fc41032b1";
String BASE_URL = "https://newsapi.org/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
Call<NewsModal> call;
if (category.equals("All")){
call = retrofitAPI.getAllNews(url);
}else {
call = retrofitAPI.getNewsByCategory(categoryURL);
}
call.enqueue(new Callback<NewsModal>() {
#Override
public void onResponse(Call<NewsModal> call, Response<NewsModal> response) {
NewsModal newsModal = response.body();
loadingPB.setVisibility(View.GONE);
ArrayList<Articles> articles = newsModal.getArticles();
for (int i=0; i < articles.size(); i++) {
articlesArrayList.add(new Articles(articles.get(i).getTitle(),articles.get(i).getDescription(),articles.get(i).getUrlToImage(),articles.get(i).getUrl(),articles.get(i).getContent()));
}
newsRVAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<NewsModal> call, Throwable t) {
Toast.makeText(MainActivity.this, "Fail to get news", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onCategoryClick(int position) {
String category = categoryRVModalArrayList.get(position).getCategory();
getNews(category);
}
}
NewsModal.java
package com.example.newsapp;
import java.util.ArrayList;
public class NewsModal {
private int totalResults;
private String status;
private ArrayList<Articles> articles;
public NewsModal(int totalResults, String status, ArrayList<Articles> articles) {
this.totalResults = totalResults;
this.status = status;
this.articles = articles;
}
public int getTotalResults() {
return totalResults;
}
public void setTotalResults(int totalResults) {
this.totalResults = totalResults;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public ArrayList<Articles> getArticles() {
return articles;
}
public void setArticles(ArrayList<Articles> articles) {
this.articles = articles;
}
}
Articles.java
package com.example.newsapp;
public class Articles {
private String title;
private String description;
private String urlToImage;
private String url;
private String content;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Articles(String title, String description, String urlToImage, String url, String content) {
this.title = title;
this.description = description;
this.urlToImage = urlToImage;
this.url = url;
this.content = content;
}
}
The error is on MainActivity.java:84 at for loop not getting the size of articles or not getting the value from newsModal.getArticles() don't know what is the real cause for this error.

How to implement searchview in recyclerview which based on SQLite? - Android

I am Building Android application which stores the patient details in SQLite database and shows this data in recyclerview, Now i want to add searchview for my recyclerview, plz help me to implement this one.
I am working on this project with the help of this youtube tutorial Series - https://youtube.com/playlist?list=PLSrm9z4zp4mGK0g_0_jxYGgg3os9tqRUQ
Here is my MainActivity Class
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
MyDatabaseHelper myDB;
ArrayList<String> _id, name, disease, medicine, mobile, address, day, month, year;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
myDB = new MyDatabaseHelper(MainActivity.this);
_id = new ArrayList<>();
name = new ArrayList<>();
disease = new ArrayList<>();
medicine = new ArrayList<>();
mobile = new ArrayList<>();
address = new ArrayList<>();
day = new ArrayList<>();
month = new ArrayList<>();
year = new ArrayList<>();
storeDataInArrays();
customAdapter = new CustomAdapter(MainActivity.this, _id, name, disease, medicine, mobile, address, day, month, year);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}else{
while (cursor.moveToNext()){
_id.add(cursor.getString(0));
name.add(cursor.getString(1));
disease.add(cursor.getString(2));
medicine.add(cursor.getString(3));
mobile.add(String.valueOf(cursor.getLong(4)));
address.add(cursor.getString(5));
day.add(cursor.getString(6));
month.add(cursor.getString(7));
year.add(cursor.getString(8));
}
}
}
}
here is my AddActivity Class
package com.example.myclinic;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class AddActivity extends AppCompatActivity {
EditText name_input, disease_input, medicine_input, mobile_input, address_input, day_input, month_input, year_input;
Button add_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
name_input = findViewById(R.id.name_input);
disease_input = findViewById(R.id.disease_input);
medicine_input = findViewById(R.id.medicine_input);
mobile_input = findViewById(R.id.mobile_input);
address_input = findViewById(R.id.address_input);
day_input = findViewById(R.id.day_input);
month_input = findViewById(R.id.month_input);
year_input = findViewById(R.id.year_input);
add_button = findViewById(R.id.add_button);
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate = formatter.format(date);
day_input.setText(strDate.substring(0,2));
month_input.setText(strDate.substring(3,5));
year_input.setText(strDate.substring(6,10));
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(name_input.getText().toString()) || TextUtils.isEmpty(disease_input.getText().toString())) {
name_input.setHint("Patient Name* (Mandatory)");
disease_input.setHint("Disease* (Mandatory)");
Toast.makeText(AddActivity.this,
"Failed!", Toast.LENGTH_SHORT).show();
} else {
try {
MyDatabaseHelper myDB = new MyDatabaseHelper(AddActivity.this);
myDB.addPatient(name_input.getText().toString().trim(),
disease_input.getText().toString().trim(),
medicine_input.getText().toString().trim(),
Long.parseLong("0" + mobile_input.getText().toString().trim()),
address_input.getText().toString().trim(),
Integer.parseInt(day_input.getText().toString().trim()),
Integer.parseInt(month_input.getText().toString().trim()),
Integer.parseInt(year_input.getText().toString().trim()));
} catch (Exception e) {
Toast.makeText(AddActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
here is MyDatabaseHelper Class
package com.example.myclinic;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.google.android.material.shape.ShapeAppearanceModel;
public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "PatientList.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "patients";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_DISEASE = "disease";
private static final String COLUMN_MEDICINES = "medicines";
private static final String COLUMN_MOBILE = "mobile";
private static final String COLUMN_ADDRESS = "address";
private static final String COLUMN_DAY = "day";
private static final String COLUMN_MONTH = "month";
private static final String COLUMN_YEAR = "year";
public MyDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query =
"CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_DISEASE + " TEXT, " +
COLUMN_MEDICINES + " TEXT, " +
COLUMN_MOBILE + " INTEGER, " +
COLUMN_ADDRESS + " TEXT, " +
COLUMN_DAY + " INTEGER, " +
COLUMN_MONTH + " INTEGER, " +
COLUMN_YEAR + " INTEGER);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addPatient(String pname, String pdisease, String pmedicines, Long pmobile, String paddress, int pday, int pmonth, int pyear){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, pname);
cv.put(COLUMN_DISEASE, pdisease);
cv.put(COLUMN_MEDICINES, pmedicines);
cv.put(COLUMN_MOBILE, pmobile.longValue());
cv.put(COLUMN_ADDRESS, paddress);
cv.put(COLUMN_DAY, pday);
cv.put(COLUMN_MONTH, pmonth);
cv.put(COLUMN_YEAR, pyear);
long result = db.insert(TABLE_NAME, null, cv);
if(result == -1) {
Toast.makeText(context, "Failed!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Added Successfully...", Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null) cursor = db.rawQuery(query, null);
return cursor;
}
}
here is CustomAdapter Class
package com.example.myclinic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.security.PrivateKey;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
private ArrayList _id, name, disease, medicine, mobile, address, day, month, year;
CustomAdapter(Context context, ArrayList _id, ArrayList name, ArrayList disease,
ArrayList medicine, ArrayList mobile, ArrayList address, ArrayList day, ArrayList month, ArrayList year){
this.context = context;
this._id = _id;
this.name = name;
this.disease = disease;
this.medicine = medicine;
this.mobile = mobile;
this.address = address;
this.day = day;
this.month = month;
this.year = year;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.id_txt.setText(String.valueOf(_id.get(position)));
holder.name_txt.setText(String.valueOf(name.get(position)));
holder.disease_txt.setText(String.valueOf(disease.get(position)));
holder.medicine_txt.setText(String.valueOf(medicine.get(position)));
holder.mobile_txt.setText(String.valueOf(mobile.get(position)));
holder.address_txt.setText(String.valueOf(address.get(position)));
holder.day_txt.setText(String.valueOf(day.get(position)));
holder.month_txt.setText(String.valueOf(month.get(position)));
holder.year_txt.setText(String.valueOf(year.get(position)));
}
#Override
public int getItemCount() {
return _id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id_txt, name_txt, disease_txt, medicine_txt, mobile_txt, address_txt, day_txt, month_txt, year_txt;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id_txt = itemView.findViewById(R.id.id_txt);
name_txt = itemView.findViewById(R.id.name_txt);
disease_txt = itemView.findViewById(R.id.disease_txt);
medicine_txt = itemView.findViewById(R.id.medicine_txt);
mobile_txt = itemView.findViewById(R.id.mobile_txt);
address_txt = itemView.findViewById(R.id.address_txt);
day_txt = itemView.findViewById(R.id.day_txt);
month_txt = itemView.findViewById(R.id.month_txt);
year_txt = itemView.findViewById(R.id.year_txt);
}
}
}
For Implementing search functionality in this project, as #thinkgruen suggested me that i need to work on single arraylist instead of multiple arraylist thats why i created separate class having all my data and made arraylist of that class, and implemented filter method to that arraylist.
After that i gone throgh this youtube tutorial - https://www.youtube.com/watch?v=CTvzoVtKoJ8
I'm posting changed code here, i made old code as a comment and changed code marked as //U . Beacuse U can clearly see what changes i have made.
at first here is new class - PatientList
package com.example.myclinic;
public class PatientList {
private int _id;
private String name;
private String disease;
private String medicine;
private long mobile;
private String address;
private int day;
private int month;
private int year;
private String serialid;
public int getid() {
return _id;
}
public void setid(int _id) {
this._id = _id;
}
public String getname() {
return name;
}
public void setname (String name) {
this.name = name;
}
public String getdisease() {
return disease;
}
public void setdisease (String disease) {
this.disease = disease;
}
public String getmedicine() {
return medicine;
}
public void setmedicine (String medicine) {
this.medicine = medicine;
}
public long getmobile() {
return mobile;
}
public void setmobile (long mobile) {
this.mobile = mobile;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public int getday() {
return day;
}
public void setday(int day) {
this.day = day;
}
public int getmonth() {
return month;
}
public void setmonth(int month) {
this.month = month;
}
public int getyear() {
return year;
}
public void setyear(int year) {
this.year = year;
}
public String getserialid() {
return serialid;
}
public void setserialid (String serialid) {
this.serialid = serialid;
}
//constructor
public PatientList(int _id, String name, String disease, String medicine, long mobile, String address, int day, int month, int year, String serialid){
this._id = _id;
this.name = name;
this.disease = disease;
this.medicine = medicine;
this.mobile = mobile;
this.address = address;
this.day = day;
this.month = month;
this.year = year;
this.serialid = serialid;
}
}
After that, in Class - CustomAdapter
package com.example.myclinic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
//U
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> implements Filterable {
private Context context;
// private ArrayList _id, name, disease, medicine, mobile, address, day, month, year, serialid;
private List<PatientList> patientList = new ArrayList<>(); //U
private List<PatientList> patientListAll = new ArrayList<>();
CustomAdapter(Context context,/* ArrayList _id, ArrayList name, ArrayList disease,
ArrayList medicine, ArrayList mobile, ArrayList address, ArrayList day, ArrayList month, ArrayList year, ArrayList serialid, */
ArrayList<PatientList> patientList){
this.context = context;
/*
this._id = _id;
this.name = name;
this.disease = disease;
this.medicine = medicine;
this.mobile = mobile;
this.address = address;
this.day = day;
this.month = month;
this.year = year;
this.serialid = serialid;
*/
this.patientList = patientList; //U
this.patientListAll = new ArrayList<>(patientList);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
/*
holder.id_txt.setText(String.valueOf(_id.get(position)));
holder.name_txt.setText(String.valueOf(name.get(position)));
holder.disease_txt.setText(String.valueOf(disease.get(position)));
holder.medicine_txt.setText(String.valueOf(medicine.get(position)));
holder.mobile_txt.setText(String.valueOf(mobile.get(position)));
holder.address_txt.setText(String.valueOf(address.get(position)));
holder.day_txt.setText(String.valueOf(day.get(position)));
holder.month_txt.setText(String.valueOf(month.get(position)));
holder.year_txt.setText(String.valueOf(year.get(position)));
holder.serialid_txt.setText(String.valueOf(serialid.get(position)));
*/
PatientList plist = patientList.get(position); //U
holder.id_txt.setText(String.valueOf(plist.getid()));
holder.name_txt.setText(String.valueOf(plist.getname()));
holder.disease_txt.setText(String.valueOf(plist.getdisease()));
holder.medicine_txt.setText(String.valueOf(plist.getmedicine()));
holder.mobile_txt.setText(String.valueOf(plist.getmobile()));
holder.address_txt.setText(String.valueOf(plist.getaddress()));
holder.day_txt.setText(String.valueOf(plist.getday()));
holder.month_txt.setText(String.valueOf(plist.getmonth()));
holder.year_txt.setText(String.valueOf(plist.getyear()));
holder.serialid_txt.setText(String.valueOf(plist.getserialid()));
}
#Override
public int getItemCount() {
return patientList.size();
}
//U
#Override
public Filter getFilter() {
return filter;
}
//U
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constaint) {
List<PatientList> filteredList = new ArrayList<>();
if (constaint.toString().isEmpty()) {
filteredList.addAll(patientListAll);
} else {
for (PatientList patient : patientListAll) {
if (patient.getname().toLowerCase().contains(constaint.toString().toLowerCase())
|| patient.getserialid().toLowerCase().contains(constaint.toString().toLowerCase())
|| patient.getaddress().toLowerCase().contains(constaint.toString().toLowerCase())) {
filteredList.add(patient);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults filterResults) {
patientList.clear();
patientList.addAll((Collection<? extends PatientList>) filterResults.values);
notifyDataSetChanged();
}
};
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id_txt, name_txt, disease_txt, medicine_txt, mobile_txt, address_txt, day_txt, month_txt, year_txt, serialid_txt;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id_txt = itemView.findViewById(R.id.id_txt);
name_txt = itemView.findViewById(R.id.name_txt);
disease_txt = itemView.findViewById(R.id.disease_txt);
medicine_txt = itemView.findViewById(R.id.medicine_txt);
mobile_txt = itemView.findViewById(R.id.mobile_txt);
address_txt = itemView.findViewById(R.id.address_txt);
day_txt = itemView.findViewById(R.id.day_txt);
month_txt = itemView.findViewById(R.id.month_txt);
year_txt = itemView.findViewById(R.id.year_txt);
serialid_txt = itemView.findViewById(R.id.serialid_txt);
}
}
}
Class DatabaseHelper
package com.example.myclinic;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.google.android.material.shape.ShapeAppearanceModel;
public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "PatientList.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "patients";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_DISEASE = "disease";
private static final String COLUMN_MEDICINES = "medicines";
private static final String COLUMN_MOBILE = "mobile";
private static final String COLUMN_ADDRESS = "address";
private static final String COLUMN_DAY = "day";
private static final String COLUMN_MONTH = "month";
private static final String COLUMN_YEAR = "year";
private static final String COLUMN_SERIALID = "serialid";
public MyDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query =
"CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_DISEASE + " TEXT, " +
COLUMN_MEDICINES + " TEXT, " +
COLUMN_MOBILE + " INTEGER, " +
COLUMN_ADDRESS + " TEXT, " +
COLUMN_DAY + " INTEGER, " +
COLUMN_MONTH + " INTEGER, " +
COLUMN_YEAR + " INTEGER, " +
COLUMN_SERIALID + " TEXT);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addPatient(String pname, String pdisease, String pmedicines, Long pmobile, String paddress, int pday, int pmonth, int pyear, String pserialid){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, pname);
cv.put(COLUMN_DISEASE, pdisease);
cv.put(COLUMN_MEDICINES, pmedicines);
cv.put(COLUMN_MOBILE, pmobile.longValue());
cv.put(COLUMN_ADDRESS, paddress);
cv.put(COLUMN_DAY, pday);
cv.put(COLUMN_MONTH, pmonth);
cv.put(COLUMN_YEAR, pyear);
cv.put(COLUMN_SERIALID, pserialid);
long result = db.insert(TABLE_NAME, null, cv);
if(result == -1) {
Toast.makeText(context, "Failed!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Added Successfully...", Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null) cursor = db.rawQuery(query, null);
return cursor;
}
}
And Final changes in MainActivity.Java
package com.example.myclinic;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.SearchView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
MyDatabaseHelper myDB;
// ArrayList<String> _id, name, disease, medicine, mobile, address, day, month, year, serialid;
ArrayList<PatientList> patientList = new ArrayList<>(); //U
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
myDB = new MyDatabaseHelper(MainActivity.this);
/*
_id = new ArrayList<>();
name = new ArrayList<>();
disease = new ArrayList<>();
medicine = new ArrayList<>();
mobile = new ArrayList<>();
address = new ArrayList<>();
day = new ArrayList<>();
month = new ArrayList<>();
year = new ArrayList<>();
serialid = new ArrayList<>();
*/
storeDataInArray();
customAdapter = new CustomAdapter(MainActivity.this, patientList);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
/*
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}else{
while (cursor.moveToNext()){
_id.add(cursor.getString(0));
name.add(cursor.getString(1));
disease.add(cursor.getString(2));
medicine.add(cursor.getString(3));
mobile.add(String.valueOf(cursor.getLong(4)));
address.add(cursor.getString(5));
day.add(cursor.getString(6));
month.add(cursor.getString(7));
year.add(cursor.getString(8));
serialid.add(cursor.getString(9));
}
}
} */
void storeDataInArray(){ //U
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}else{
while (cursor.moveToNext()){
patientList.add(new PatientList(cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getLong(4),
cursor.getString(5),
cursor.getInt(6),
cursor.getInt(7),
cursor.getInt(8),
cursor.getString(9)));
}
}
}
#Override //U
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.mainmenu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
customAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
nothing changed in AddActivity.
I hope this will be helpfull to you.

How to pass data collected in arraylist from json asset file in one activity having recyclerview to another activity again having recycler view?

I have an activity named Cardview Activity which has a recycler view associated with it and i am fetching data from a JSON asset file in that. But now when i click on an item of Cardview Activity, I want to send data related to that item only to another activity i.e. People_List_Activity which is again having a recyclerView.
CardViewActivity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class CardViewActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
private RecyclerView mainRecyclerView;
private RecyclerView.Adapter mainAdapter;
private RecyclerView.LayoutManager mainLayoutManager;
private static String LOG_TAG = "CardViewActivity";
EditText inputSearchMain;
private ArrayList<CategoryModel.CategoryList> categoryLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Telephone Directory");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
categoryLists=new ArrayList<CategoryModel.CategoryList>();
categoryLists.addAll(getmcategoryset());
mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
mainRecyclerView.setHasFixedSize(true);
mainLayoutManager=new LinearLayoutManager(this);
mainRecyclerView.setLayoutManager(mainLayoutManager);
mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
mainRecyclerView.setAdapter(mainAdapter);
inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);
addTextListener();
}
public void addTextListener(){
inputSearchMain.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();
for (int i = 0; i < categoryLists.size(); i++) {
final String text = categoryLists.get(i).getCategory_name().toLowerCase();
if (text.contains(query)) {
filteredList.add(categoryLists.get(i));
}
}
mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
mainAdapter = new RecyclerViewAdapterMain(filteredList);
mainRecyclerView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged(); // data set changed
}
});
}
private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
try {
ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray categoryArray = jsonObject.getJSONArray("Category");
Log.d("getmcategoryset", "category count: "+categoryArray.length());
for (int i = 0; i < categoryArray.length(); i++)
{
JSONObject job = categoryArray.getJSONObject(i);
int categoryId = job.getInt("Category_id");
String categoryName = job.getString("Category_name");
//this is for email array
ArrayList<String> emails = new ArrayList<>();
JSONArray emailArray = job.getJSONArray("Emails");
for (int j = 0; j< emailArray.length(); j++){
emails.add(emailArray.getString(j));
}
//This i for Epabx array
ArrayList<String> epabx = new ArrayList<>();
JSONArray epabxArray = job.getJSONArray("Epabx");
for (int j = 0; j < epabxArray.length(); j++){
epabx.add(epabxArray.getString(j));
}
//This i for Category_Fax array
ArrayList<String> category_Fax = new ArrayList<>();
JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
for (int j = 0; j < category_FaxJson.length(); j++){
category_Fax.add(category_FaxJson.getString(j));
}
//This i for Persons array
ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
JSONArray personsArray = job.getJSONArray("Persons");
for (int j = 0; j < personsArray.length(); j++){
JSONObject jobIn = personsArray.getJSONObject(j);
int Person_ID = jobIn.getInt("Person_ID");
String Name = jobIn.getString("Name");
String Designation = jobIn.getString("Designation");
String Office_Phone = jobIn.getString("Office_Phone");
String Residence_Phone = jobIn.getString("Residence_Phone");
String VOIP = jobIn.getString("VOIP");
String Address = jobIn.getString("Address");
//this is for Fax array
ArrayList<String>Fax = new ArrayList<>();
JSONArray fax = jobIn.getJSONArray("Fax");
for (int k=0; k < fax.length(); k++)
{
// JSONObject jobI = fax.getString(k);
Fax.add(fax.getString(k));
}
String Ext = jobIn.getString("Ext");
personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
VOIP, Address, Fax, Ext));
}
//here your Category[] value store in categoryArrayList
categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
Log.i("categoryList size = ", ""+categoryArray.length());
}
if (categoryList != null)
{
Log.i("categoryList size = ", ""+categoryArray.length());
}
return categoryList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
}
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("DirectoryData.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
RecyclerViewAdapterMain
package com.example.android.directory;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Android on 3/17/2017.
*/
public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
private static String LOG_TAG = "categoryRecyclrVwAdptr";
private ArrayList<CategoryModel.CategoryList> mcategoryset;
private static CategoryClickListener categoryClickListener;
public static class CategoryObjectHolder extends RecyclerView.ViewHolder {
TextView category_name;
public CategoryObjectHolder(View itemView){
super(itemView);
category_name=(TextView)itemView.findViewById(R.id.category_name);
/*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
}
});
}
public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
mcategoryset = myDataset;
}
public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
return categoryObjectHolder;
}
#Override
public void onBindViewHolder(CategoryObjectHolder holder, int position) {
holder.category_name.setText(mcategoryset.get(position).getCategory_name());
}
public void addItem(CategoryModel.CategoryList dataObj, int index) {
mcategoryset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mcategoryset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mcategoryset.size();
}
public interface CategoryClickListener {
public void onItemClick(int position, View v);
}
}
People_List_Activity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class PeopleListActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people_list);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Staff List");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
}
}
RecyclerViewAdapter_People.java
package com.example.android.directory;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Android on 3/20/2017.
*/
public class RecyclerViewAdapter_People extends RecyclerView.Adapter<RecyclerViewAdapter_People.PeopleObjectHolder> {
private static String TAG = "peopleRecyclrVwAdptr";
public static class PeopleObjectHolder extends RecyclerView.ViewHolder{
TextView peopleName,peopleDesignation;
public PeopleObjectHolder(View itemView) {
super(itemView);
peopleName=(TextView)itemView.findViewById(R.id.people_name);
peopleDesignation=(TextView)itemView.findViewById(R.id.people_designation);
Log.d(TAG, "PeopleObjectHolder: ");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public PeopleObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_people_list_row,parent,false);
PeopleObjectHolder peopleObjectHolder=new PeopleObjectHolder(view);
return peopleObjectHolder;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter_People.PeopleObjectHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
CategoryModel.java:
package com.example.android.directory;
import java.util.ArrayList;
/**
* Created by Android on 3/17/2017.
*/
public class CategoryModel {
private ArrayList<CategoryList>categoryList;
public ArrayList<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public static class CategoryList{
private int Category_id;
private String Category_name;
private ArrayList<String>Emails;
private ArrayList<String>Epabx;
private ArrayList<String>Category_Fax;
private ArrayList<Persons> persons;
public CategoryList(int category_id, String category_name,
ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
ArrayList<Persons> persons) {
Category_id = category_id;
Category_name = category_name;
Emails = emails;
Epabx = epabx;
Category_Fax = category_Fax;
this.persons = persons;
}
public int getCategory_id() {
return Category_id;
}
public void setCategory_id(int category_id) {
Category_id = category_id;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
public ArrayList<String> getEmails() {
return Emails;
}
public void setEmails(ArrayList<String> emails) {
Emails = emails;
}
public ArrayList<String> getEpabx() {
return Epabx;
}
public void setEpabx(ArrayList<String> epabx) {
Epabx = epabx;
}
public ArrayList<String> getCategory_Fax() {
return Category_Fax;
}
public void setCategory_Fax(ArrayList<String> category_Fax) {
Category_Fax = category_Fax;
}
public ArrayList<Persons> getPersons() {
return persons;
}
public void setPersons(ArrayList<Persons> persons) {
this.persons = persons;
}
}
public static class Persons{
private int Person_ID;
private String Name;
private String Designation;
private String Office_Phone;
private String Residence_Phone;
private String VOIP;
private String Address;
private ArrayList<String>Fax;
private String Ext;
public Persons(int person_ID, String name, String designation, String office_Phone,
String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
Person_ID = person_ID;
Name = name;
Designation = designation;
Office_Phone = office_Phone;
Residence_Phone = residence_Phone;
this.VOIP = VOIP;
Address = address;
Fax = fax;
Ext = ext;
}
public int getPerson_ID() {
return Person_ID;
}
public void setPerson_ID(int person_ID) {
Person_ID = person_ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public String getOffice_Phone() {
return Office_Phone;
}
public void setOffice_Phone(String office_Phone) {
Office_Phone = office_Phone;
}
public String getResidence_Phone() {
return Residence_Phone;
}
public void setResidence_Phone(String residence_Phone) {
Residence_Phone = residence_Phone;
}
public String getVOIP() {
return VOIP;
}
public void setVOIP(String VOIP) {
this.VOIP = VOIP;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public ArrayList<String> getFax() {
return Fax;
}
public void setFax(ArrayList<String> fax) {
Fax = fax;
}
public String getExt() {
return Ext;
}
public void setExt(String ext) {
Ext = ext;
}
}
}
how can i send the Person_Id, Name and Designation to the People_List_Activity ? Please help as i am stuck in the code.
You can send using Intent , by passing your data in Bundle and then pass Bundle into Intent Extras.When you go form one Activity to another .
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key1",value1);
bundle.putString("key2",value2);
bundle.putString("key3",value3);
intent.putExtras(bundle)
startActvity(intent);
And You can retrieve Data in next Activity OnCreate():
Bundle bundle = getIntent().getExtras();
String value1 = bundle.getString("key1");
String value2 = bundle.getString("key2");
String value3 = bundle.getString("key3");

Arraylist keeps overwriting the last entry i added

sorry for troubling you, i am new at android, and i need a little help. I am doing a simple ampplication in which you sign up some people to a club. What it keeps happening is that the last person i add to the arraylist overwries the old one. I really donĀ“t know what it could be. If you can help i would be grateful.
AltaSocio.java
package com.example.polideportivo1;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class AltaSocio extends Activity {
Socios nuevosSocio = new Socios(0,"","","","","","","","",0,0,"");
VariablesGlobales vb = new VariablesGlobales();
private EditText editDocumento;
private EditText editApellido;
private EditText editNombre;
private CheckBox checkBoxM;
private CheckBox checkBoxF;
private EditText editCivil;
private Spinner Nacionalidad;
private EditText Nacimiento;
private EditText Domicilio;
private Spinner Localidad;
private EditText Celular;
private EditText TelFijo;
private EditText Correo;
String miNacionalidad;
String miLocalidad;
ArrayList<Socios> socios = vb.getSocios();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alta_socio2);
editDocumento = (EditText)findViewById(R.id.editDocumento);
editApellido = (EditText)findViewById(R.id.editApellido);
editNombre = (EditText)findViewById(R.id.editNombre);
editCivil = (EditText)findViewById(R.id.editCivil);
Nacimiento = (EditText)findViewById(R.id.editNacimiento);
Domicilio = (EditText)findViewById(R.id.editDomicilio);
Celular = (EditText)findViewById(R.id.editCelular);
TelFijo = (EditText)findViewById(R.id.editFijo);
Correo = (EditText)findViewById(R.id.editCorreo);
checkBoxM = (CheckBox)findViewById(R.id.checkM);
checkBoxF = (CheckBox)findViewById(R.id.checkF);
Nacionalidad = (Spinner)findViewById(R.id.spinnerNacionalidad);
Localidad = (Spinner)findViewById(R.id.spinnerLocalidad);
final Button BtnCrear = (Button)findViewById(R.id.botonCrear);
final Button BtnCerrar = (Button)findViewById(R.id.buttonAtras);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Nacionalidad, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
Nacionalidad.setAdapter(adapter);
Nacionalidad.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
miNacionalidad = Nacionalidad.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.Localidad, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_item);
Localidad.setAdapter(adapter2);
Localidad.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
miLocalidad = Localidad.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
}
public void grabar(View v) {
nuevosSocio.setCI(Integer.parseInt(editDocumento.getText().toString()));
nuevosSocio.setApellido(editApellido.getText().toString());
nuevosSocio.setNombre(editNombre.getText().toString());
nuevosSocio.setEstadoCivil(editCivil.getText().toString());
DateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
DateFormat DataSocio;
try {
String Fecha =(Nacimiento.getText().toString());
formateador.parse(Fecha);
nuevosSocio.setFechaNacimiento(Fecha);
}
catch (ParseException e)
{
Toast g = Toast.makeText(this, "Formato Fecha no valido", Toast.LENGTH_LONG);
}
//nuevosSocio.setFechaNacimiento(Fecha);
nuevosSocio.setDomicilio(Domicilio.getText().toString());
nuevosSocio.setTelefonoCelular(Integer.parseInt(Celular.getText().toString()));
nuevosSocio.setTelefonoFijo(Integer.parseInt(TelFijo.getText().toString()));
nuevosSocio.setCorreo(Correo.getText().toString());
if (checkBoxM.isChecked()) {
nuevosSocio.setSexo("Masculino");
} else {
nuevosSocio.setSexo("Femenino");
}
nuevosSocio.setNacionalidad(miNacionalidad);
nuevosSocio.setLocalidad(miLocalidad);
socios.add(nuevosSocio);
nuevosSocio = new Socios(0,"","","","","","","","",0,0,"");
Toast t = Toast.makeText(this, "Los datos fueron grabados",
Toast.LENGTH_SHORT);
t.show();
finish();
}
}
Socio.java
package com.example.polideportivo1;
import java.sql.Date;
import android.graphics.Bitmap;
import android.widget.CheckBox;
import android.widget.ImageView;
public class Socios {
private int CI;
private String Nombre;
private String Apellido;
private String Sexo;
private String EstadoCivil;
private String Nacionalidad;
private String FechaNacimiento;
private String Domicilio;
private String Localidad;
private int TelefonoCelular;
private int TelefonoFijo;
private String DireccionCorreo;
public Socios(int CI, String Nombre, String Apellido, String Sexo, String EstadoCivil,
String Nacionalidad, String FechaNacimiento, String Domicilio, String Localidad, int TelefonoCelular, int TelefonoFijo, String DireccionCorreo) {
this.CI = CI;
this.Nombre = Nombre;
this.Apellido = Apellido;
this.Sexo = Sexo;
this.EstadoCivil = EstadoCivil;
this.Nacionalidad = Nacionalidad;
this.FechaNacimiento = FechaNacimiento;
this.Domicilio = Domicilio;
this.Localidad = Localidad;
this.TelefonoCelular = TelefonoCelular;
this.TelefonoFijo = TelefonoFijo;
this.DireccionCorreo = DireccionCorreo;
}
public int obtenerCI() {
return CI;
}
public String obtenerNombre() {
return Nombre;
}
public String obtenerApellido() {
return Apellido;
}
public String obtenerSexo() {
return Sexo;
}
public void setSexo() {
this.Sexo = Sexo;
}
public String obtenerNacionalidad() {
return Nacionalidad;
}
public String obtenerEstadoCivil() {
return EstadoCivil;
}
public String obtenerFechaNacimiento() {
return FechaNacimiento;
}
public String obtenerDomicilio() {
return Domicilio;
}
public String obtenerLocalidad() {
return Localidad;
}
public int obtenerCelular() {
return TelefonoCelular;
}
public int obtenerTelefonoFijo() {
return TelefonoFijo;
}
public String obtenerCorreo() {
return DireccionCorreo;
}
public void setCI(int parseInt) {
this.CI = parseInt;
}
public void setApellido(String string) {
this.Apellido = string;
}
public void setNombre(String string) {
this.Nombre = string;
}
public void setEstadoCivil(String string) {
this.EstadoCivil = string;
}
public void setDomicilio(String string) {
this.Domicilio = string;
}
public void setTelefonoCelular(int parseInt) {
this.TelefonoCelular = parseInt;
}
public void setTelefonoFijo(int parseInt) {
this.TelefonoFijo = parseInt;
}
public void setCorreo(String string) {
this.DireccionCorreo = string;
}
public void setSexo(String string) {
this.Sexo = string;
}
public void setNacionalidad(String miNacionalidad) {
this.Nacionalidad = miNacionalidad;
}
public void setLocalidad(String miLocalidad) {
this.Localidad = miLocalidad;
}
public void setFechaNacimiento(String string) {
this.FechaNacimiento = string;
}
}
Every time you called the grabar to add the user you have to create a new Socio object. Using the same references will only change object's content

How do I iterate the ArrayList created in ViewRestaurantList to place markers on the map?

Restaurant Class
package sg.edu.rp.c345.a01.hungrycomehere;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
public class Restaurant {
// Declarations Fields
String name;
String address;
String phoneNumber;
String email;
String url;
String openingHours;
String closingHours;
GeoPoint latLong;
// Constructor generated from Fields
public Restaurant(String name, String address, String phoneNumber,
String email, String url, String openingHours, String closingHours,
GeoPoint latLong) {
super();
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.email = email;
this.url = url;
this.openingHours = openingHours;
this.closingHours = closingHours;
this.latLong = latLong;
}
// A mapping from String values to various Parcelable types.
// Construct from Bundle
public Restaurant(Bundle b) {
name = b.getString("restaurantName");
address = b.getString("restaurantAddress");
phoneNumber = b.getString("restaurantPhoneNumber");
email = b.getString("restaurantEmail");
url = b.getString("restaurantUrl");
openingHours = b.getString("restaurantOpeningHrs");
closingHours = b.getString("restaurantClosingHrs");
latLong = new GeoPoint(b.getInt("restaurantLat"), b.getInt("restaurantLng"));
}
// Convert into bundle
public Bundle getBundle() {
Bundle bundle = new Bundle();
bundle.putString("restaurantName", name);
bundle.putString("restaurantAddress", address);
bundle.putString("restaurantUrl", url);
bundle.putString("restaurantEmail", email);
bundle.putString("restaurantPhoneNumber", phoneNumber);
bundle.putString("restaurantOpeningHrs", openingHours);
bundle.putString("restaurantClosingHrs", closingHours);
bundle.putInt("restaurantLat", latLong.getLatitudeE6());
bundle.putInt("restaurantLng", latLong.getLongitudeE6());
return bundle;
}
// Get, Set, toString!
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOpeningHours() {
return openingHours;
}
public void setOpeningHours(String openingHours) {
this.openingHours = openingHours;
}
public String getClosingHours() {
return closingHours;
}
public void setClosingHours(String closingHours) {
this.closingHours = closingHours;
}
public GeoPoint getLatLong() {
return latLong;
}
public void setLatLong(GeoPoint latLong) {
this.latLong = latLong;
}
#Override
public String toString() {
return "Restaurant [name=" + name + ", address=" + address
+ ", phoneNumber=" + phoneNumber + ", email=" + email
+ ", url=" + url + ", openingHours=" + openingHours
+ ", closingHours=" + closingHours + ", latLong=" + latLong
+ "]";
}
}
Restaurant List
package sg.edu.rp.c345.a01.hungrycomehere;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.android.maps.GeoPoint;
public class ViewRestaurantList extends ListActivity {
// Declarations
ListView restaurantListView;
ArrayList<Restaurant> restaurantList = new ArrayList<Restaurant>();
ArrayList<String> restaurantName = new ArrayList<String>();
ArrayAdapter<String> restaurantAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurant_list_view);
setRestaurant("Ban Leong Wah Hoe Seafood",
"122 Casuarina Road, Singapore", "64522824",
"contact#wahhoe-seafood.com", "http://www.wahhoe-seafood.com",
"5:00 PM", "1:30 AM", new GeoPoint(1376700, 103828170));
setRestaurant(
"Ngee Fou Restaurant (Hakka) Ampang Yong Tou Foo",
"928 Upper Thomson Road, Singapore",
"64521801",
null,
"http://www.hungrygowhere.com/singapore/ngee_fou_restaurant_hakka_ampang_yong_tou_foo/",
"9:30 AM", "7:30 PM", new GeoPoint(1399455, 103817878));
setElements();
}
// Create onListItemClick method
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Intent viewRestaurant = new Intent(getBaseContext(),
ViewRestaurantMap.class);
viewRestaurant.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Put all restaurants' data across activities.
viewRestaurant.putExtras(restaurantList.get(position).getBundle());
startActivity(viewRestaurant);
}
// Populate list
private void setElements() {
restaurantListView = getListView();
registerForContextMenu(restaurantListView);
restaurantAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, restaurantName);
restaurantListView.setAdapter(restaurantAdapter);
}
private void setRestaurant(String name, String address, String phoneNumber,
String email, String url, String openingHours, String closingHours,
GeoPoint latLong) {
restaurantList.add(new Restaurant(name, address, phoneNumber, email,
url, openingHours, closingHours, latLong));
restaurantName.add(name);
}
}
Restaurant Map
package sg.edu.rp.c345.a01.hungrycomehere;
import java.util.List;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
public class ViewRestaurantMap extends MapActivity {
// Declarations
static final private int MAP_VIEW = Menu.FIRST;
static final private int SAT_VIEW = Menu.FIRST + 1;
MapView map;
MapController myMapController;
MyLocationOverlay myLocationOverlay;
List<Overlay> mapOverlays;
Drawable marker;
HelloItemizedOverlay itemizedOverlay;
Bundle restaurants;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurant_map);
// Get Intents from ViewShoeList and Views from layout
restaurants = new Bundle(getIntent().getExtras());
// MapView and Controller
map = (MapView) findViewById(R.id.map);
map.setBuiltInZoomControls(true);
myMapController = map.getController();
myMapController.setZoom(11);
myMapController.setCenter(new GeoPoint(1352083, 103819836));
// MyLocationOverlay
myLocationOverlay = new MyLocationOverlay(this, map);
myLocationOverlay.enableMyLocation();
map.getOverlays().add(myLocationOverlay);
// Get Overlays
mapOverlays = map.getOverlays();
marker = this.getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new HelloItemizedOverlay(marker);
// Add Markers on Restaurants
for (int i = 0; i < restaurants.size(); i++) {
}
}
// Create Options menu
#Override
public boolean onCreateOptionsMenu(Menu optionsMenu) {
super.onCreateOptionsMenu(optionsMenu);
// Create and add new menu items.
MenuItem itemMap = optionsMenu.add(0, MAP_VIEW, Menu.NONE,
R.string.mapview);
MenuItem itemSatellite = optionsMenu.add(0, SAT_VIEW, Menu.NONE,
R.string.satview);
itemMap.setIcon(R.drawable.mapview);
itemSatellite.setIcon(R.drawable.satelliteview);
return true;
}
// Execute option's action based on user click.
#Override
public boolean onOptionsItemSelected(MenuItem optionItem) {
super.onOptionsItemSelected(optionItem);
switch (optionItem.getItemId()) {
case (MAP_VIEW): {
map.setSatellite(false);
return true;
}
case (SAT_VIEW): {
map.setSatellite(true);
return true;
}
}
return false;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
You can create a method in your ItemizedOverlay class to add all restaurant objects. For this, your ItemizedOverlay will need to have an internal ArrayList bound to the overlay by overriding the createItem method. It might also help to subclass OverlayItem for your restaurant map items. Hope that helps.

Categories