I am trying to make a basic shopping cart android application
Here is how the code looks
Items.java
public class Items extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
Intent intent = getIntent();
int subCategoryId = intent.getIntExtra("parameter_name", 1);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
String url = "http://146.185.178.83/resttest/subCategories/" + subCategoryId +"/items/";
new JSONTask().execute(url);
}
public class JSONTask extends AsyncTask<String, String, List<ItemModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<ItemModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<ItemModel> itemModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
ItemModel itemModel = gson.fromJson(finalObject.toString(), ItemModel.class);
itemModelList.add(itemModel);
}
return itemModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<ItemModel> result) {
super.onPostExecute(result);
dialog.dismiss();
ItemAdapter adapter = new ItemAdapter(getApplicationContext(), R.layout.row_item, result);
lvUsers.setAdapter(adapter);
}
}
public class ItemAdapter extends ArrayAdapter {
public List<ItemModel> itemModelList;
private int resource;
private LayoutInflater inflater;
public ItemAdapter(Context context, int resource, List<ItemModel> objects) {
super(context, resource, objects);
itemModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.tvItemName = (TextView) convertView.findViewById(R.id.tvItemName);
holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvItemName.setText(itemModelList.get(position).getItemName());
holder.tvPrice.setText("Rs " + itemModelList.get(position).getSalesRate());
final String itemName = itemModelList.get(position).getItemName();
final String salesRate = itemModelList.get(position).getSalesRate();
Intent intent = new Intent(Items.this, CartDisplay.class);
intent.putExtra("itemName", itemName);
intent.putExtra("salesRate", salesRate);
return convertView;
}
class ViewHolder{
private TextView tvItemName;
private TextView tvPrice;
}
}
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem add_item = menu.findItem(R.id.action_add_item);
add_item.setVisible(false);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.testmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.action_show_cart:
cartMenuItem();
break;
}
return true;
}
private void cartMenuItem() {
Intent intent = new Intent(Items.this, CartDisplay.class);
startActivity(intent);
finish();
}
}
CartDisplay.java
public class CartDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_cart_display);
TextView tvItemName = (TextView) findViewById(R.id.tvItemName);
TextView tvSalesRate = (TextView) findViewById(R.id.tvSalesRate);
TextView tvTotalAmount = (TextView) findViewById(R.id.tvTotalAmount);
Intent intent = getIntent();
String itemName = intent.getStringExtra("itemName");
tvItemName.setText(itemName);
String salesRate = intent.getStringExtra("salesRate");
tvSalesRate.setText("RS"+salesRate);
tvTotalAmount.setText("Total: RS"+salesRate);
}
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem show_cart = menu.findItem(R.id.action_show_cart);
show_cart.setVisible(false);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.testmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.action_add_item:
addMenuItem();
break;
}
return true;
}
private void addMenuItem() {
Intent intent = new Intent(this, Categories.class);
startActivity(intent);
finish();
}
}
Here is how the item layout looks
Here is how the CartDisplay layout looks
The issue at the moment is I am not able to send data to CartDisplay
Activity also I need help with implementing few other things
In Items Activity, how do I make EditText between - and + button to
show the number based on the clicks on + and - button it should not
go below zero (ie like no negative figures its like x1 or x2 or x3
etc)
When pressed on itemAddToCart button (its the cart button inside the
item list ) , it must add item to cart and not move to CartDisplay
activity , it must also send the no of items added (because its
needed there ie in CartDisplay layout needs to show this in EditText
there).
When there is an update in Cart (i.e like once we have Added an item
to cart) need to show update on cart icon on Action bar with little
+1 or where there is two items in cart +2 or anything similar , the cart icon is an menu_item if pressed here it will take you to
CartDisplay activity how to code this ?
Also how to code it to send info of multiple selected items to cart?
when pressed on cart icon it must show the updates and the last
activity must be paused ? now i have menu item in CartDisplay
Activity which will take me back to Items Activity , so i can add
more items to the cart , the process continues until i checkout or
Clear cart .
Also I need help to write code for Clear cart .
My project is open source at github there you can see my full code
Related
I'm currently building an app which use a RealmRecyclerViewAdapter for displaying the elements inside Realm.
I was looking into implementing the Filterable interface, which I managed to do (thanks to those answers: Link 1 Link 2) but now I have a side effect: when I'm filtering, the Adapter shows all the elements, even if they doesn't match with the filter. Also, the excluded element does show incorrect information. When I close the SearchView, everything is back to normal.
Here is the Activity when I call the Adapter:
public class MainActivity extends AppCompatActivity {
private Realm realm;
HabitCardAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
setUIMode();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set the title inside the top bar for this activity.
// I'm not doing it inside the Manifest because it changes the app's name
setTitle(R.string.MainActivityTitle);
// Bottom App Bar setup
BottomAppBar bottomAppBar = findViewById(R.id.bottomAppBar);
cutBottomAppEdge(bottomAppBar); // Diamond shape
// Add listener to Stats button inside the bottom app bar
MenuItem statsMenuItem = bottomAppBar.getMenu().findItem(R.id.statsMenuItem);
statsMenuItem.setOnMenuItemClickListener(item -> {
if(item.getItemId() == R.id.statsMenuItem){
Intent i = new Intent(getApplicationContext(), StatsActivity.class);
startActivity(i);
return true;
}
return false;
});
// FAB button setup
FloatingActionButton fab = findViewById(R.id.fabAddButton);
fab.setOnClickListener(view -> {
Intent intent = new Intent(getBaseContext(), CreateHabitActivity.class);
startActivity(intent);
});
RecyclerView rv = findViewById(R.id.habitCardRecyclerView);
TextView emptyMessage = findViewById(R.id.mainEmptyHabitListMessage);
realm = Realm.getDefaultInstance();
RealmResults<Habit> results = realm.where(Habit.class).sort("id").findAll();
results.addChangeListener(habits -> {
if (habits.size() > 0) {
rv.setVisibility(View.VISIBLE);
emptyMessage.setVisibility(View.GONE);
} else {
emptyMessage.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
}
});
//this is necessarily because it is not changed yet
if (results.size() > 0) {
rv.setVisibility(View.VISIBLE);
emptyMessage.setVisibility(View.GONE);
} else {
emptyMessage.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
}
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(layoutManager);
adapter = new HabitCardAdapter(results, true, this, realm);
rv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.top_app_bar_menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.searchMenuItem).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
adapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (adapter != null) {
adapter.getFilter().filter(newText);
return true;
}
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.searchMenuItem:
return true;
case R.id.settingMenuItem:
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent); //FIXME: animazione
return true;
case R.id.aboutMenuItem:
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
builder.setTitle(getString(R.string.about_us_title));
builder.setMessage(getString(R.string.about_us_message));
builder.setIcon(R.drawable.ic_sprout_fg_small);
builder.setPositiveButton("OK", (dialogInterface, i) -> {
dialogInterface.dismiss();
});
builder.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Set the Night/Light UI. On the first run of the app, the user get the Light UI.
*/
private void setUIMode() {
SharedPreferences preferences = getSharedPreferences(SettingsActivity.SHARED_PREFS_FILE, MODE_PRIVATE);
int pref = preferences.getInt(SettingsActivity.SHARED_PREFS_DARK_MODE, AppCompatDelegate.MODE_NIGHT_NO);
AppCompatDelegate.setDefaultNightMode(pref);
}
private void cutBottomAppEdge(BottomAppBar bar) {
BottomAppBarTopEdgeTreatment topEdge = new SproutBottomAppBarCutCornersTopEdge(
bar.getFabCradleMargin(),
bar.getFabCradleRoundedCornerRadius(),
bar.getCradleVerticalOffset());
MaterialShapeDrawable babBackground = (MaterialShapeDrawable) bar.getBackground();
//It requires 1.1.0-alpha10
babBackground.setShapeAppearanceModel(
babBackground.getShapeAppearanceModel()
.toBuilder()
.setTopEdge(topEdge)
.build());
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeAllChangeListeners();
realm.close();
}
}
Here is the HabitCardAdapter which extends RealmRecyclerViewAdapter:
public class HabitCardAdapter extends RealmRecyclerViewAdapter<Habit, HabitCardAdapter.ViewHolder> implements Filterable {
Context ct;
OrderedRealmCollection<Habit> list;
Realm mRealm;
public HabitCardAdapter(#Nullable OrderedRealmCollection<Habit> data, boolean autoUpdate, Context context, Realm realm) {
super(data, autoUpdate); //autoUpdate to true
ct = context;
list = data;
mRealm = realm;
}
#Override
public int getItemCount() {
return this.list.size();
}
#NonNull
#Override
public HabitCardAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
//TODO: inflatare diversi tipi di carte a seconda del habitType
View view = inflater.inflate(R.layout.fragment_habit_counter_card, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull HabitCardAdapter.ViewHolder holder, int position) {
final Habit habit = getItem(position);
if (habit != null) {
holder.setHabit(habit);
holder.editHabitButton.setOnClickListener(view -> {
Intent intent = new Intent(ct, EditHabitActivity.class);
intent.putExtra("HABIT_ID", habit.getId());
//TODO: Aggiungere l'animazione
ct.startActivity(intent);
});
holder.checkButton.setOnClickListener(view -> {
int habitId = habit.getId();
int newRepValue = habit.getRepetitions() + 1;
int maxReps = habit.getMaxRepetitions();
Log.d("Testing", newRepValue + " - " + maxReps);
if (newRepValue <= habit.getMaxRepetitions()) {
habit.getRealm().executeTransaction(realm -> {
Habit result = realm.where(Habit.class).equalTo("id", habitId).findFirst();
if (result != null) {
result.setRepetitions(newRepValue);
String newLabel = "Completato " + newRepValue + " volte su " + maxReps;
holder.progressLabel.setText(newLabel);
}
});
}
});
}
}
public void filterResults(String text) {
text = text == null ? null : text.toLowerCase().trim();
if (text == null || "".equals(text)) {
updateData(mRealm.where(Habit.class).sort("id").findAllAsync());
} else {
updateData(mRealm.where(Habit.class).contains("title", text).sort("id").findAllAsync());
}
}
public Filter getFilter() {
HabitFilter filter = new HabitFilter(this);
return filter;
}
private class HabitFilter extends Filter {
private final HabitCardAdapter adapter;
private HabitFilter(HabitCardAdapter adapter) {
this.adapter = adapter;
}
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
return new FilterResults();
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
adapter.filterResults(charSequence.toString());
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView habitTitle;
ProgressBar progressBar;
TextView progressLabel;
ImageButton editHabitButton;
Button checkButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
habitTitle = itemView.findViewById(R.id.habitCardTitle);
editHabitButton = itemView.findViewById(R.id.counterHabitEditButton);
progressBar = itemView.findViewById(R.id.counterHabitProgressBar);
checkButton = itemView.findViewById(R.id.checkButton);
progressLabel = itemView.findViewById(R.id.counterHabitProgressLabel);
}
void setHabit(Habit habit) {
this.habitTitle.setText(habit.getTitle());
this.progressBar.setProgress(habit.getRepetitions());
this.progressBar.setMax(habit.getMaxRepetitions());
this.progressLabel.setText("Completato " + habit.getRepetitions() + " volte su " + habit.getMaxRepetitions()); //FIXME: sposta la stringa
}
}
}
I don't really know if this is the way to go for this problem, but it's now behaving as expected so I'll share the solution here.
Inside the HabitCardAdapter I added another OrderedRealmCollection<Habit> member, called filteredList, while list holds the whole data. In the costructor both of filteredList and list are tied to the data passed to the constructor, but while filteredList will be modified by the query, list will not (probably putting it to final is the best practice). Then everything in the Adapter will now reference to filteredList instead of list, and when the SearchView is selected and the query is up, filteredList will get the data, and then updateData(filteredList) will be called.
Here is what I changed:
public class HabitCardAdapter extends RealmRecyclerViewAdapter<Habit, HabitCardAdapter.ViewHolder> implements Filterable {
Context ct;
OrderedRealmCollection<Habit> list;
OrderedRealmCollection<Habit> filteredList;
Realm mRealm;
...
}
public HabitCardAdapter(#Nullable OrderedRealmCollection<Habit> data, Context context, Realm realm) {
super(data, true, true);
ct = context;
list = data;
filteredList = data;
mRealm = realm;
setHasStableIds(true);
}
Probably the error was here in getItemCount(), when the filteredListsize was smaller than the list one, but since I didn't have any reference to filteredList, I didn't have any way to change that size, and so the Adapter would continue to show - for example - 6 views while I was querying for 3. Having it as a properly class member it let me make this:
#Override
public int getItemCount() {
return this.filteredList.size();
}
public void filterResults(String text) {
text = text == null ? null : text.toLowerCase().trim();
if (text == null || "".equals(text)) {
filteredList = list;
} else {
filteredList = mRealm.where(Habit.class).beginsWith("title", text, Case.INSENSITIVE).sort("id").findAll();
}
updateData(filteredList);
}
I have a spinner that i select data from which goes into a arraylist that is used with a list view to display the contents. I know the values are going into the Arraylist but when it comes to the list view it does not work correctly.
What happens is the first item will load in fine, but when i add another item the previous one disappears, while the new one is displayed one position down from the previous one, this repeats for each one i added.
create itinerary code:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
private boolean saved;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
private ProgressDialog pDialog;
private List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
private LayoutInflater myInflator;
private View myView;
private DBManager db;
private myAdapter adapter;
private int ID;
private String NAME;
private String LOCATION;
private String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
private ListView ls;
private TextView TextTime;
private String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
saved = false;
ls = (ListView)findViewById(R.id.listCreateItinerary);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
(this).registerForContextMenu(ls);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(v.getId()== R.id.listCreateItinerary){
this.getMenuInflater().inflate(R.menu.context_menu,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.menuDelete:
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (saved == false) {
if (id == R.id.go_home) {
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
}
else if(saved == true){
if (id == R.id.go_home) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void addTransportToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
saved = true;
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(ID,NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
System.out.println(categoriesList.get(i));
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all attraction categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
// new GetTransport().execute();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
return myView;
}
public void deleteItineraryItem(){
Entities.remove(ID);
finalEntities.remove(ID);
loadAttractions();
}
}
}
The public void loadAttractions(){..., is the medthod code that updates the list view, the 2 methods above it relate to separate buttons and add the spinner item to the array list (Entities), thank you to anyone who can help me.
instead of:
#Override
public Object getItem(int position) {
return null;
}
try this code:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listItem.get(position); //return list item
}
I have done some series of research about how to make each item of the listview in fragment activity to move to another activity having getView() from swipeListadapter. The codes below contain the tab fragment containing the swipe listadapter for the list view and the setonitemclicklistener.
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
The code below is my fragment tab class
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.177.53.152/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) vi.findViewById(R.id.list);
listView.setBackgroundColor(Color.WHITE);
swipeRefreshLayout = (SwipeRefreshLayout) vi.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
//getView().setOnClickListener();
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
return vi;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
switch(position) {
case 1:
intent = new Intent(getActivity().getApplicationContext(), New1.class);
startActivity(intent);
break;
case 2:
intent = new Intent(getActivity().getApplicationContext(), New2.class);
startActivity(intent);
break;
default:
intent = new Intent(getActivity().getApplicationContext(), New3.class);
startActivity(intent);
}
}
});
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
In a nutshell, whenever I click any of the item listview, the app crashes and system logcat is not giving any clue to that. I want to be able to click an item on the listview in d fragment and to be directed to a new activity. Any help will be appreciated. Thanks.
I have a list view containing few fields coming from back end. One feed is 'number of likes'.
When I click on any list row it opens one activity for that row, there like button in that activity. When user presses like it get appended on server.
Now the problem is it should show incremented value in the list view when user go back to list view activity. How to do that?
NOTE: Like counter is incremented if I close the app and start it again.
I tried to call on Create method again from on Resume method but it produces duplicate copy of rows every time list view activity is remusmed.
Here is my list activity code.
public class MainActivity extends Activity {
// Session Manager Class
SessionManager session;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "MY_URL";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
{
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setThumbnailUrl(obj.getString("image"));
movie.setTitle(obj.getString("title"));
movie.setDate(obj.getString("date"));
movie.setVideo(obj.getString("video"));
movie.setLikes(obj.getInt("likes"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creating unique ID
final String deviceId = Settings.Secure.getString(this.getContentResolver(),
Settings.Secure.ANDROID_ID);
Toast.makeText(this, deviceId, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
/**
* Call this function whenever you want to check user login
* This will redirect user to LoginActivity is he is not
* logged in
* */
session.checkLogin();
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
// ImageView thumbNail = (ImageView)view.findViewById(R.id.thumbnail);
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String likes = ((TextView)view.findViewById(R.id.likes)).getText().toString();
String date = ((TextView)view.findViewById(R.id.date)).getText().toString();
String video = ((TextView) view.findViewById(R.id.video)).getText().toString();
String idd = ((TextView) view.findViewById(R.id.idd)).getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(), MovieDetailActivity.class);
// in.putExtra("THUMB", thumbNail.toString());
in.putExtra("TITLE", title);
in.putExtra("LIKES", likes);
in.putExtra("DATE", date);
in.putExtra("VIDEO", video);
in.putExtra("IDD", idd);
in.putExtra("UNIQUEID",deviceId);
//in.putExtra(TAG_URL,"url");
// in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
}
);
// Creating volley request obj
enter code here
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setThumbnailUrl(obj.getString("image"));
movie.setTitle(obj.getString("title"));
movie.setDate(obj.getString("date"));
movie.setVideo(obj.getString("video"));
movie.setLikes(obj.getInt("likes"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView likes = (TextView) convertView.findViewById(R.id.likes);
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView video = (TextView) convertView.findViewById(R.id.video);
TextView id = (TextView) convertView.findViewById(R.id.idd);
//TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
date.setText(m.getDate());
video.setText(m.getVideo());
likes.setText(String.valueOf(m.getLikes()));
id.setText(String.valueOf(m.getId()));
return convertView;
// Listview on item click listener
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
Requested implementation using a SortedList and RecyclerView:
Here is the example I used to build mine.
This is my slightly more complex code that includes sorting via a SearchView in the toolbar. You can use the example in the above link if you want the example without the sorting. The control logic is in my Presenter class that manages this adapter and the Fragment:
public class AdapterInstitutionList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// lists to control all items and items visible after sorting
private SortedList<MInstitutionInfo> visibleList;
private ArrayList<MInstitutionInfo> allItems;
// my fragment and the presenter
private FInstitutionSelection fInstitutionSelection;
private PInstitutionList presenter;
public AdapterInstitutionList(PInstitutionList pInstitutionSelection, FInstitutionSelection fInstitutionSelection) {
// get ref to fragment, presenter, and create new callback for sortedlist
this.fInstitutionSelection = fInstitutionSelection;
presenter = pInstitutionSelection;
visibleList = new SortedList<>(MInstitutionInfo.class, new InstitutionListCallback());
allItems = new ArrayList<>();
}
// inflate your list item view here
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listitem_institution, parent, false);
return new InstitutionViewHolder(view);
}
// on binding, you populate your list item with the values, onclickhandle, etc
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
InstitutionViewHolder institutionViewHolder = (InstitutionViewHolder) viewHolder;
final MInstitutionInfo institutionInfo = visibleList.get(position);
institutionViewHolder.setInstitutionInfo(institutionInfo);
institutionViewHolder.populateTextView();
institutionViewHolder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presenter.onInstitutionSelected(institutionInfo);
}
});
}
#Override
public int getItemCount() {
return visibleList.size();
}
// my utility function for the presenter/fragment
public MInstitutionInfo get(int position) {
return visibleList.get(position);
}
public int add(MInstitutionInfo item) {
return visibleList.add(item);
}
public int indexOf(MInstitutionInfo item) {
return visibleList.indexOf(item);
}
public void updateItemAt(int index, MInstitutionInfo item) {
visibleList.updateItemAt(index, item);
}
public void addAll(List<MInstitutionInfo> items) {
visibleList.beginBatchedUpdates();
try {
for (MInstitutionInfo item : items) {
visibleList.add(item);
allItems.add(item);
}
} finally {
visibleList.endBatchedUpdates();
}
}
public void addAll(MInstitutionInfo[] items) {
addAll(Arrays.asList(items));
}
public boolean remove(MInstitutionInfo item) {
return visibleList.remove(item);
}
public MInstitutionInfo removeItemAt(int index) {
return visibleList.removeItemAt(index);
}
public void clearVisibleList() {
visibleList.beginBatchedUpdates();
try {
// remove items at end to remove unnecessary array shifting
while (visibleList.size() > 0) {
visibleList.removeItemAt(visibleList.size() - 1);
}
} finally {
visibleList.endBatchedUpdates();
}
}
public void clearAllItemsList() {
allItems.clear();
}
public void filterList(String queryText) {
clearVisibleList();
visibleList.beginBatchedUpdates();
try {
String constraint = queryText.toLowerCase();
for (MInstitutionInfo institutionInfo : allItems) {
if (institutionInfo.getName() != null && institutionInfo.getName().toLowerCase().contains(constraint)) {
visibleList.add(institutionInfo);
}
}
} finally {
visibleList.endBatchedUpdates();
}
}
public void clearFilter() {
if (visibleList.size() == allItems.size()) {
return;
}
clearVisibleList();
visibleList.beginBatchedUpdates();
try {
for (MInstitutionInfo institutionInfo : allItems) {
visibleList.add(institutionInfo);
}
} finally {
visibleList.endBatchedUpdates();
}
}
// the callback for the SortedList
// this manages the way in which items are added/removed/changed/etc
// mine is pretty simple
private class InstitutionListCallback extends SortedList.Callback<MInstitutionInfo> {
#Override
public int compare(MInstitutionInfo o1, MInstitutionInfo o2) {
return o1.getName().compareTo(o2.getName());
}
#Override
public void onInserted(int position, int count) {
notifyItemRangeInserted(position, count);
}
#Override
public void onRemoved(int position, int count) {
notifyItemRangeRemoved(position, count);
}
#Override
public void onMoved(int fromPosition, int toPosition) {
notifyItemMoved(fromPosition, toPosition);
}
#Override
public void onChanged(int position, int count) {
notifyItemRangeChanged(position, count);
}
#Override
public boolean areContentsTheSame(MInstitutionInfo oldItem, MInstitutionInfo newItem) {
return oldItem.getName().equals(newItem.getName());
}
#Override
public boolean areItemsTheSame(MInstitutionInfo item1, MInstitutionInfo item2) {
return item1.getName().equals(item2.getName());
}
}
// this is the view holder that is used for the list items
private class InstitutionViewHolder extends RecyclerView.ViewHolder {
public View parent;
public TextView tvName;
public MInstitutionInfo institutionInfo;
public InstitutionViewHolder(View itemView) {
super(itemView);
parent = itemView;
tvName = (TextView) itemView.findViewById(R.id.tv_institution_listitem_name);
}
public MInstitutionInfo getInstitutionInfo() {
return institutionInfo;
}
public void setInstitutionInfo(MInstitutionInfo institutionInfo) {
this.institutionInfo = institutionInfo;
}
public void populateTextView() {
if (tvName != null && institutionInfo != null && institutionInfo.getName() != null) {
tvName.setText(institutionInfo.getName());
}
}
}
You simply instantiate this adapter and assign it to your RecyclerView
myRecyclerView.setAdapter(myAdapter);
When you call any of the batched updates, the list will automatically update itself in the UI. So when you get your initial data, just call addAll(yourData) and the RecyclerView will auto populate the list. When you get updated data, you just call addAll(yourNewData) and the RecyclerView will automatically add new items and remove the new non-existent items leaving you with a fully updated list. You will need to be sure to implement the SorteList.Callback methods compare(...), areContentsTheSame(...), areItemsTheSame(...) properly to ensure that this behaves as you want it to when adding/removing items.
Please let me know if you need any more help. Frankly, this implementation type for updated and sorted data is extremely smooth.
I have a class which retrives data from my database and displays it in a listview using simple adapter
public class ViewExs extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://www.lamia.byethost18.com/get_all_ex.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "ID_exercise";
private static final String TAG_NAME = "ID_exercise";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_exs);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), EditProductActivity.class);
startActivity(i);
/* // getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);*/
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewExs.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewExs.this, productsList,
R.layout.item_list_3, new String[] {TAG_NAME},
new int[] { R.id.pid});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
i want to use a custom adapter rather than the simple adapter .. here is my custom adapter
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
TextView textView;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.item_list_3, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_list_3, parent, false);
final TextView textView = (TextView) rowView.findViewById(R.id.pid);
textView.setText(values[position]);
return rowView;
}
}
how i do this part of code
ListAdapter adapter = new SimpleAdapter(
ViewExs.this, productsList,
R.layout.item_list_3, new String[] {TAG_NAME},
new int[] { R.id.pid});
// updating listview
setListAdapter(adapter);
in the custom adapter ?
can someone help please ?
Just use the MySimpleArrayAdapter in your method and set the adapter -
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable()
{
public void run()
{
/**
* Updating parsed JSON data into ListView
* */
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(ViewExs.this,
new String[] {TAG_NAME});
// updating listview
setListAdapter(adapter);
}
});
}
Suppose your arrays of values is String[] values, then
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(
ViewExs.this,values);
setListAdapter(adapter);
Hi I used a custom array adapter like the one below, it's just a sample. But I hope it helps. It displays data that was sent to it using an ArrayList from an fragment where it is displayed.
public class MovieAdapter extends ArrayAdapter<Movie> {
private Context context;
private List<Movie> movies;
public MovieAdapter(Context context, List<Movie> movies) {
super(context, R.layout.movie_layout, movies);
this.context = context;
this.movies = movies;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View movieView = convertView;
if (movieView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
movieView = inflater.inflate(R.layout.movie_layout, parent, false);
}
movieView.setTag(movies.get(position));
TextView txtTitle = (TextView) movieView.findViewById(R.id.txtTitle);
TextView txtDate = (TextView) movieView.findViewById(R.id.txtDate);
RatingBar ratingBar = (RatingBar) movieView
.findViewById(R.id.ratingBar);
txtTitle.setText(movies.get(position).MovieTitle);
txtDate.setText("Date Viewed: " + movies.get(position).dateViewed);
ratingBar.setIsIndicator(true);
ratingBar.setNumStars(movies.get(position).rating);
ratingBar.setRating(movies.get(position).rating);
return movieView;
}
}
The fragment
public class MyListFragment extends Fragment {
Movie movie;
MovieAdapter adapter;
MovieSelectedListener callBack;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
ListView movieList = (ListView) view.findViewById(R.id.movieList);
movieList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView movie = (TextView) view.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onMovieSelected(title);
}
});
if (getArguments() != null)
movie = (Movie) getArguments().getSerializable("Movie");
Log.v("PASSED", "Got here");
adapter = new MovieAdapter(getActivity(), movie.movies);
movieList.setAdapter(adapter);
movieList.setLongClickable(true);
movieList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent,
final View view, int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder dialog = new AlertDialog.Builder(
getActivity());
dialog.setMessage("Are you sure you want to delete this movie?");
dialog.setTitle("Alert Message");
dialog.setCancelable(false);
dialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
TextView movie = (TextView) view
.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onDeleteSelected(title, adapter);
}
});
dialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
});
dialog.show();
return false;
}
});
return view;
}
public interface MovieSelectedListener {
public void onMovieSelected(String movie);
public void onDeleteSelected(String movie, MovieAdapter adapter);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
;
try {
callBack = (MovieSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement MovieSelectedListener");
}
}
public void sortTitle() {
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.MovieTitle.compareTo(rhs.MovieTitle);
}
});
adapter.notifyDataSetChanged();
}
public void sortDateViewed() {
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.dateViewed.compareTo(rhs.dateViewed);
}
});
adapter.notifyDataSetChanged();
}
public void sortRating() {
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return ((Integer) lhs.rating).compareTo(rhs.rating);
}
});
adapter.notifyDataSetChanged();
}
}