I have an issue updateing TextView in Android App.What I do is, when "+" button is pressed, RecycleView opens, then I click on the item retrived there from Kinvey.Then I pass name of the item Clicked to the Main activity.From Main activity i can LOG that data when I run the app for the seckond time (First time value is null since i did not clicked an item in RecycleView), but I can not set TextView with that Value(TextView stay empty)?3rd time when i run the app, retrived value is null again.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Testiraj";
private RecyclerView rv;
public Context context;
private TextView TextViewGymName;
private TextView TextViewVisitorsNumber;
private List<AllGyms> mVisitors;
public static final String MY_PREFS_NAME = "MyPrefsFile";
public String mRVPickedItem;
public String restoredText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextViewGymName = (TextView) findViewById(R.id.gymName);
TextViewVisitorsNumber = (TextView) findViewById(R.id.gymVisitors);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
restoredText = prefs.getString("name", "nothing");
if(restoredText!=null){
Log.v(TAG,restoredText);
TextViewGymName.setText(restoredText);
}
else{
Log.v(TAG, "null" +" "+ restoredText);
}
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
Intent intenti=getIntent();
Bundle b = intenti.getExtras();
if(b!=null){
mRVPickedItem = (String) b.get("NAME_OF_THE_STRING");
final Client mKinveyClient = new Client.Builder("KEY", "KEY_APP"
, this.getApplicationContext()).build();
final Query query = new Query();
query.equals("name", mRVPickedItem);
query.equals("visitors");
AsyncAppData<AllGyms> searchedEvents = mKinveyClient.appData("allGyms", AllGyms.class);
searchedEvents.get(query, new KinveyListCallback<AllGyms>() {
#Override
public void onSuccess(AllGyms[] event) {
ArrayList<AllGyms> arrayList = new ArrayList<AllGyms>(Arrays.asList(event));
String[] array = new String[arrayList.size()];
mVisitors = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
array[i] = arrayList.get(i).getVisitors();
//allGymses.add(new AllGyms(test[i].getName()));
//Log.v(TAG, "received " + array[i]);
TextViewVisitorsNumber.setText(array[i]);
}
}
#Override
public void onFailure(Throwable error) {
Log.e(TAG, "failed to query ", error);
}
});
}
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", mRVPickedItem);
editor.apply();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
restoredText = prefs.getString("name", mRVPickedItem);
TextViewGymName.setText(restoredText);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, `RecyclerViewActivity.class);`
startActivity(intent);
}
});
}
#Override
public void onDestroy() {
super.onDestroy(); // Always call the superclass method first
}
#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;
}
#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 (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
RecycleView Activity:
package com.fittoloc.uros.gymloced;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.kinvey.android.AsyncAppData;
import com.kinvey.android.Client;
import com.kinvey.android.callback.KinveyListCallback;
import com.kinvey.android.callback.KinveyUserCallback;
import com.kinvey.java.Query;
import com.kinvey.java.User;
import com.kinvey.java.core.KinveyClientCallback;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RecyclerViewActivity extends AppCompatActivity {
private List<AllGyms> allGymses;
private RecyclerView rv;
public Context context;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
rv=(RecyclerView)findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
initializeRecycleView();
rv.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
}
})
);
}
private void initializeRecycleView() {
//ovde resiti problem!!!!
final Client mKinveyClient = new Client.Builder("KEY", "KEY"
, this.getApplicationContext()).build();
mKinveyClient.user().login(new KinveyUserCallback() {
#Override
public void onFailure(Throwable t) {
CharSequence text = "Login error.";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(User u) {
CharSequence text = "Welcome back!";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
final AllGyms teretane = new AllGyms();
Query myQuery = mKinveyClient.query();
myQuery.equals ("name");
AsyncAppData<AllGyms> myGyms = mKinveyClient.appData("allGyms", AllGyms.class);
myGyms.get(myQuery, new KinveyListCallback<AllGyms>() {
#Override
public void onSuccess(AllGyms[] results) {
ArrayList <AllGyms> arrayList = new ArrayList<AllGyms>(Arrays.asList(results));
String [] array = new String[arrayList.size()];
allGymses = new ArrayList<>();
for(int i = 0 ; i < arrayList.size() ; i++){
array[i] = arrayList.get(i).getName();
//allGymses.add(new AllGyms(test[i].getName()));
allGymses.add((new AllGyms(array[i])));
//Log.v(TAG, "received " + array[i]);
initializeAdapter();
}
//Log.v(TAG, "received " + results + " allGyms");
}
#Override
public void onFailure(Throwable error) {
Log.e(TAG, "failed to fetchByFilterCriteria", error);
}
});
//
}
private void initializeAdapter(){
RVAdapter adapter = new RVAdapter(allGymses,context);
rv.setAdapter(adapter);
}
}
RecyleItemClickListener:
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
private static final String TAG = "MyActivity";
private String position;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
Related
The code I've done was followed closely by a few YouTube tutorials. I'm designing an Age of Empires app that takes in the data from a public API. When the user progresses through the pages then different parts of the API data are shown. What I wanted it to do was get the data from the main activity (where the API is retrieved) and put some of its many data into the UniqueUnit page. It's using something called serializable which I can't quite understand how it works yet.
For the record, it works in getting the data from page 'DetailedCivilization' but just completely breaks on 'UniqueUnit'page.
MainActivity.java
package com.example.ageofempires2;
import ...
public class MainActivity extends AppCompatActivity {
public static final String TAG = "tag";
RecyclerView itemList;
Adapter adapter;
List<Civilizations> all_civilizations;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Civilizations menu");
all_civilizations = new ArrayList<>();
itemList = findViewById(R.id.itemList);
itemList.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(this, all_civilizations);
itemList.setAdapter(adapter);
getJsonData();
}
private void getJsonData() {
String URL = "https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray civilizations = response.getJSONArray("civilizations");
JSONObject civilizationsData = civilizations.getJSONObject(0);
Log.d(TAG, "onResponse "+ civilizationsData);
for (int i=0; i< civilizationsData.length();i++){
JSONObject civilization = civilizations.getJSONObject(i);
Civilizations v = new Civilizations();
v.setName(civilization.getString("name"));
v.setArmy_type(civilization.getString("army_type"));
v.setExpansion(civilization.getString("expansion"));
v.setCivilization_bonus(civilization.getString("civilization_bonus"));
v.setUnique_unit(civilization.getString("unique_unit"));
all_civilizations.add(v);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse" + error.getMessage());
}
});
requestQueue.add(objectRequest);
}
}
Adapter.java
package com.example.ageofempires2;
import ...
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Civilizations> allCivilizations;
private Context context;
public Adapter(Context ctx, List<Civilizations> civilizationsData){
this.allCivilizations = civilizationsData;
this.context = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.civilization_view,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.titleName.setText(allCivilizations.get(position).getName());
holder.vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putSerializable("civilizationsData", allCivilizations.get(position));
Intent i = new Intent(context, DetailedCivilization.class);
i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return allCivilizations.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleName;
TextView expansionName;
View vv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
titleName = itemView.findViewById(R.id.civilizationUniqueUnits);
expansionName = itemView.findViewById(R.id.civilizationUnitDescription);
vv = itemView;
}
}
}
Civilizations.java
package com.example.ageofempires2;
import java.io.Serializable;
public class Civilizations implements Serializable {
private String name;
private String expansion;
private String army_type;
private String civilization_bonus;
private String unique_unit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExpansion() {
return expansion;
}
public void setExpansion(String expansion) {
this.expansion = expansion;
}
public String getArmy_type() {
return army_type;
}
public void setArmy_type(String army_type) {
this.army_type = army_type;
}
public String getCivilization_bonus() {
return civilization_bonus;
}
public void setCivilization_bonus(String civilization_bonus) {this.civilization_bonus = civilization_bonus; }
public String getUnique_unit() {
return unique_unit;
}
public void setUnique_unit(String unique_unit) {this.unique_unit = unique_unit; }
}
UniqueUnits.java
package com.example.ageofempires2;
import ...
public class UniqueUnit extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unique_unit);
getSupportActionBar().setTitle("Unique Unit");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent incomingIntent = getIntent();
Bundle incomingName = incomingIntent.getExtras();
Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData");
Log.d(TAG, "onCreate: IDK MAN IT SHOULD WORK??" +incomingName);
TextView unit = findViewById(R.id.civilizationUnitDescription);
unit.setText(v.getUnique_unit());
}
}
DetailedCivilization.java
package com.example.ageofempires2;
import ...
public class DetailedCivilization extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations v = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit();
}
});
}
private void activityTech(){
Intent intent = new Intent(this, UniqueTech.class);
startActivity(intent);
}
private void activityUnit(){
Intent intent = new Intent(this, UniqueUnit.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
Solutions is
private void activityUnit(Civilizations civ){
Bundle b = new Bundle();
b.putSerializable("civilizationsData", civ)
Intent intent = new Intent(this, UniqueUnit.class);
intent.putExtras(b);
startActivity(intent);
}
In DetailedCivilization.java
Rename v from line Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData"); to civ or something more descriptive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations civ = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit(civ);
}
});
}
And pass Civilizations when you call activityUnit function
Basically you forgot to pass Civilizations when you go from DetailedCivilization.java to UniqueUnits.java
I am having four tab in my View pager I have search in google but I can,t found any solution when Swipe my view pager it work fine like 1-2-3-4 but when I try to swipe reverse 4-3-2-1 than my data get lost or you can say my adapter get lost.My View Pager is inside Activity.My Data is lost when I go to next page and back then back my data is lost.
My Main Activity is:
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#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 (id == R.id.action_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
My Fragment is
public class ImageListFragment extends Fragment {
String category_Name, Category_ID, Product_ID, Product_Name,
Product_Image, Product_Price, Product_Sale, Cart;
public static final String STRING_IMAGE_URI = "ImageUri";
public static final String STRING_IMAGE_POSITION = "ImagePosition";
private static MainActivity mActivity;
ArrayList<SingleItemModel> singleItemModels;
RecyclerView recyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCategoryone();
Fresco.initialize(getContext());
mActivity = (MainActivity) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
recyclerView = (RecyclerView) inflater.inflate(R.layout.layout_recylerview_list, container, false);
return recyclerView;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder> {
// private String[] mValues;
private ArrayList<SingleItemModel> mValues;
private RecyclerView mRecyclerView;
public static class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final SimpleDraweeView mImageView;
public final LinearLayout mLayoutItem;
public final ImageView mImageViewWishlist;
TextView iTemName, itemDescription, itemPrice;
public ViewHolder(View view) {
super(view);
mView = view;
mImageView = (SimpleDraweeView) view.findViewById(R.id.image1);
mLayoutItem = (LinearLayout) view.findViewById(R.id.layout_item);
mImageViewWishlist = (ImageView) view.findViewById(R.id.ic_wishlist);
iTemName = (TextView) view.findViewById(R.id.itemName);
itemDescription = (TextView) view.findViewById(R.id.itemDescription);
itemPrice = (TextView) view.findViewById(R.id.itemPrice);
}
}
public SimpleStringRecyclerViewAdapter(RecyclerView recyclerView, ArrayList<SingleItemModel> items) {
mValues = items;
mRecyclerView = recyclerView;
}
#Override
public ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder(view);
}
#Override
public void onViewRecycled(ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder) {
if (holder.mImageView.getController() != null) {
holder.mImageView.getController().onDetach();
}
if (holder.mImageView.getTopLevelDrawable() != null) {
holder.mImageView.getTopLevelDrawable().setCallback(null);
//
}
}
#Override
public void onBindViewHolder(final ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder, final int position) {
SingleItemModel singleItemModel = mValues.get(position);
holder.iTemName.setText(singleItemModel.getCategory_Name());
final Uri uri = Uri.parse(singleItemModel.getProduct_Image());
holder.mImageView.setImageURI(uri);
holder.itemPrice.setText(singleItemModel.getProduct_Price());
holder.itemDescription.setText(singleItemModel.getProduct_Sale());
}
#Override
public int getItemCount() {
return mValues.size();
}
}
public void getCategoryone() {
final RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://proaudiobrands.com/app/feature.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("shabina shopping response", response);
try {
singleItemModels = new ArrayList<>();
JSONObject mainObj = new JSONObject(response);
Log.d("shabina ", response);
JSONArray Feature_product = mainObj.getJSONArray("Feature_product");
for (int i = 0; i < Feature_product.length(); i++) {
JSONObject Feature_Product = Feature_product.getJSONObject(i);
String Category_Namee = Feature_Product.getString("Category_Namee");
String Category_IDs = Feature_Product.getString("Category_IDs");
JSONArray Product_List = Feature_Product.getJSONArray("Product_List");
for (int j = 0; j < Product_List.length(); j++) {
JSONObject Category_Name = Product_List.getJSONObject(j);
if (Category_Name.getString("Category_Name").equals("Microphones")) {
category_Name = Category_Name.getString("Category_Name");
Category_ID = Category_Name.getString("Category_ID");
Product_ID = Category_Name.getString("Product_ID");
Product_Name = Category_Name.getString("Product_Name");
Product_Image = Category_Name.getString("Product_Image");
Product_Price = Category_Name.getString("Product_Price");
Product_Sale = Category_Name.getString("Product_Sale");
Cart = Category_Name.getString("Cart");
Log.e("sushil Category_Name", category_Name + " " + Category_ID + " " + Product_ID + " " + Product_Name + " " + Product_Image + " " + Product_Price + " " + Product_Sale + " " + Cart);
SingleItemModel singleItemModel1 = new SingleItemModel(category_Name, Category_ID, Product_ID, Product_Name, Product_Image, Product_Price, Product_Sale, Cart);
singleItemModels.add(singleItemModel1);
}
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(new ImageListFragment.SimpleStringRecyclerViewAdapter(recyclerView, singleItemModels));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("method", "feature");
params.put("userId", "PRO1");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
}
Replace your MainActivity with below
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
viewPager.setOffscreenPageLimit(4);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#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 (id == R.id.action_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
I'm making a voting system in an android app that uses firebase as it's backend. I'm in the process of getting the user's vote status from their history, updating the view accordingly, and responding to vote touches on the buttons. The problem I'm having is that when a user clicks on the up or down vote buttons it redraws the listview, sometimes omitting two of the options, and always moving the scrolling of the view back up to the top. Can I update the data inside of a listview without completely redrawing that listview? If so, how?
MovieActivity.java
public class MovieActivity extends AppCompatActivity {
private static final String KEY_IMDB = "KEY_IMDB";
private ImageView mPosterImageView;
private TextView mTitleTextView;
private TextView mYearTextView;
private TextView mSummaryTextView;
private ListView triggerListView;
private ArrayList<Trigger> mTriggerPrefList;
private Movie mMovie;
private LinkedList<Trigger> resultList;
DatabaseReference movieDB;
DatabaseReference userDB;
DatabaseReference thisMovieDB;
DatabaseReference triggerDB;
DatabaseReference adminDB;
FirebaseAuth mFirebaseAuth;
FirebaseUser mUser;
ArrayList<Trigger> mTriggerList;
String imdbID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie);
mPosterImageView = (ImageView) findViewById(R.id.posterImageView);
mTitleTextView = (TextView) findViewById(R.id.titleTextView);
mYearTextView = (TextView) findViewById(R.id.yearTextView);
mSummaryTextView = (TextView) findViewById(R.id.summaryTextView);
triggerListView = (ListView) findViewById(R.id.triggerListView);
mFirebaseAuth = FirebaseAuth.getInstance();
mUser = mFirebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
imdbID = intent.getStringExtra("ID_KEY");
final String keyTitle = intent.getStringExtra("TITLE_KEY");
final String keyYear = intent.getStringExtra("YEAR_KEY");
final String keyPoster = intent.getStringExtra("POSTER_KEY");
try {
getMovieDetails(imdbID, new Runnable() {
#Override
public void run() {
CheckForTriggerValues(new Runnable() {
#Override
public void run() {
populateTriggers(new Runnable() {
#Override
public void run() {
populatePrefs(new Runnable() {
#Override
public void run() {
reOrderList(new Runnable() {
#Override
public void run() {
Movie passMovie = new Movie();
passMovie.setImdbID(imdbID);
passMovie.setPosterURL(keyPoster);
passMovie.setYear(keyYear);
passMovie.setTitle(keyTitle);
TriggerAdapter adapter = new TriggerAdapter(MovieActivity.this, resultList, passMovie, imdbID );
triggerListView.setAdapter(adapter);
}
});
}
});
}
});
}
});
}
});
} catch (JSONException e) {
e.printStackTrace();
}
thisMovieDB = movieDB.child(imdbID);
triggerDB = thisMovieDB.child("Triggers");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_IMDB, imdbID);
}
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
imdbID = intent.getStringExtra("ID_KEY");
}
private void getMovieDetails(String imdbID, Runnable runnable) throws JSONException {
String apiKey = OMITTED;
String theURL = "http://www.omdbapi.com/?i=" + imdbID + "&apikey=" + apiKey;
final OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(theURL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String jsonData = response.body().string();
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Movie movie = parseMovieDetails(jsonData);
updateMovieUI(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
});
runnable.run();
}
private Movie parseMovieDetails(String jsonData) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonData);
Movie movie = new Movie();
movie.setPosterURL(jsonObject.getString("Poster"));
movie.setTitle(jsonObject.getString("Title"));
movie.setYear(jsonObject.getString("Year"));
movie.setSummary(jsonObject.getString("Plot"));
mMovie = movie;
return movie;
}
private void updateMovieUI(Movie movie){
Context mContext = getApplicationContext();
mSummaryTextView.setText(movie.getSummary());
mYearTextView.setText(movie.getYear());
mTitleTextView.setText(movie.getTitle());
Picasso.with(mContext).load(movie.getPosterURL()).into(mPosterImageView);
}
private void populatePrefs(final Runnable runnable) {
mTriggerPrefList = new ArrayList<>();
mFirebaseAuth = FirebaseAuth.getInstance();
mUser = mFirebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
thisMovieDB = movieDB.child(imdbID);
thisMovieDB.child("Details").setValue(mMovie);
triggerDB = thisMovieDB.child("Triggers");
userDB.child(mUser.getUid()).child("preferences").child("trigger").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot triggerSnapshot : dataSnapshot.getChildren()) {
String name = String.valueOf(triggerSnapshot.child("triggerName").getValue());
Trigger trigger = new Trigger();
trigger.setTriggerName(name);
trigger.setTriggerVotesTotal(0);
trigger.setTriggerVotesYes(0);
mTriggerPrefList.add(trigger);
}
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
imdbID = intent.getStringExtra("ID_KEY");
runnable.run();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void populateTriggers(final Runnable runnable) {
mTriggerList = new ArrayList<>();
mFirebaseAuth = FirebaseAuth.getInstance();
mUser = mFirebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
thisMovieDB = movieDB.child(imdbID);
thisMovieDB.child("Details").setValue(mMovie);
triggerDB = thisMovieDB.child("Triggers");
triggerDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mTriggerList.clear();
for (DataSnapshot triggerSnapshot : dataSnapshot.getChildren()) {
Trigger trigger = triggerSnapshot.getValue(Trigger.class);
mTriggerList.add(trigger);
}
runnable.run();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void reOrderList(Runnable runnable) {
resultList = new LinkedList<>();
for (Trigger triggerA : mTriggerList) {
boolean found = false;
for (Trigger triggerB : mTriggerPrefList) {
if (triggerB.getTriggerName().equals(triggerA.getTriggerName())) {
found = true;
}
}
if (found) {
resultList.add(triggerA);
}
}
mTriggerList.removeAll(resultList);
resultList.addAll(mTriggerList);
runnable.run();
}
private void CheckForTriggerValues(final Runnable runnable) {
adminDB.child("triggerList").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<Map<String, Object>> genericTypeIndicator = new GenericTypeIndicator<Map<String, Object>>() {};
final Map<String, Object> triggerList = dataSnapshot.getValue(genericTypeIndicator);
triggerDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (Map.Entry<String, Object> entry : triggerList.entrySet())
{
if (dataSnapshot.hasChild(entry.getKey())){
}
else {
Trigger trigger1 = new Trigger(entry.getKey(), 0, 0);
triggerDB.child(trigger1.getTriggerName()).setValue(trigger1);
}
}
runnable.run();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
int isTrue(Boolean boolDown, Boolean boolUp) {
int x = 0;
if (boolUp) {
x = 1;
}
if (boolDown) {
x = -1;
}
return x;
}
}
TriggerAdapter.java
package me.paxana.cwnet.Adapters;
import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.andremion.counterfab.CounterFab;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
import me.paxana.cwnet.Model.Movie;
import me.paxana.cwnet.Model.Trigger;
import me.paxana.cwnet.R;
import me.paxana.cwnet.ui.AdminPanelActivity;
import me.paxana.cwnet.ui.MovieActivity;
/**
* Created by paxie on 10/11/17.
*/
public class TriggerAdapter extends BaseAdapter {
private Context mContext;
private List<Trigger> mTriggers;
private Movie mMovie;
private String mImdbID;
private String mTitle;
private String mYear;
private String mPosterURL;
private DatabaseReference movieDB;
private DatabaseReference userDB;
private DatabaseReference triggerDB;
private DatabaseReference adminDB;
public TriggerAdapter(Context context, List<Trigger> triggerList, Movie movie, String imdbID){
mContext = context;
this.mTriggers = triggerList;
mMovie = movie;
mImdbID = imdbID;
mTitle = movie.getTitle();
mYear = movie.getYear();
mPosterURL = movie.getPosterURL();
};
public TriggerAdapter(Context context, List<Trigger> triggerList) {
mContext = context;
this.mTriggers = triggerList;
}
#Override
public int getCount() {
return this.mTriggers.size();
}
#Override
public Object getItem(int i) {
return mTriggers.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, final ViewGroup viewGroup) {
final ViewHolder holder;
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
final String mUserId = user.getUid();
final Trigger trigger = mTriggers.get(i);
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.trigger_list_item, null);
holder = new ViewHolder();
holder.triggerName = view.findViewById(R.id.triggerName);
holder.upButton = view.findViewById(R.id.mTriggerButtonUp);
holder.downButton = view.findViewById(R.id.mTriggerButtonDown);
holder.total = view.findViewById(R.id.triggerCounter);
view.setTag(holder);
}
else {
holder = (ViewHolder) view.getTag();
}
holder.triggerName.setText(trigger.getTriggerName());
if (mContext instanceof AdminPanelActivity) {
holder.upButton.setVisibility(View.INVISIBLE);
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adminDB.child("triggerList").child(trigger.getTriggerName()).removeValue();
int i = mTriggers.indexOf(trigger);
mTriggers.remove(i);
TriggerAdapter.this.notifyDataSetChanged();
}
});
}
if (mContext instanceof MovieActivity) {
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
int userVote = dataSnapshot.getValue(Integer.class);
if (userVote == 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
}
else {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
}
neitherButtonIsSelected(holder, trigger, mUserId);
}
if (userVote == 1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons, null));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
}
else {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
}
upButtonIsSelected(holder, trigger, mUserId);
}
if (userVote == -1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons, null));
}
else {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons));
}
downButtonIsSelected(holder, trigger, mUserId);
}
}
else {
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(0);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
holder.total.setText(String.valueOf(trigger.getTriggerVotesYes()));
holder.upButton.setCount(trigger.getTriggerVotesYes());
if (trigger.getTriggerVotesTotal() != 0){
holder.total.setText(String.valueOf(trigger.getTriggerVotesTotal()));
int downButtonCount = (trigger.getTriggerVotesTotal() - trigger.getTriggerVotesYes());
holder.downButton.setCount(downButtonCount);
}
return view;
}
private static class ViewHolder {
TextView triggerName;
CounterFab upButton;
CounterFab downButton;
TextView total;
}
private void neitherButtonIsSelected(final ViewHolder holder, final Trigger trigger, final String mUserId) {
holder.upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
triggerDB = movieDB.child(mImdbID).child("Triggers").child(trigger.getTriggerName());
triggerDB.child("triggerVotesYes").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
triggerDB.child("triggerVotesTotal").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
}
});
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
triggerDB.child("triggerVotesTotal").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
}
});
}
private void upButtonIsSelected(final ViewHolder holder, final Trigger trigger, final String mUserId) {
holder.upButton.setOnClickListener(null);
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
triggerDB = movieDB.child(mImdbID).child("Triggers").child(trigger.getTriggerName());
triggerDB.child("triggerVotesYes").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count - 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(-1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
holder.downButton.getBackground().setAlpha(127);
}
});
}
});
}
private void downButtonIsSelected(final ViewHolder holder, final Trigger trigger, final String mUserId) {
holder.downButton.setOnClickListener(null);
holder.upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
triggerDB = movieDB.child(mImdbID).child("Triggers").child(trigger.getTriggerName());
triggerDB.child("triggerVotesYes").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
holder.downButton.getBackground().setAlpha(127);
}
});
}
});
}
}
Following things might help you.
Use android:stackFromBottom="true" in the xml of your ListView
Instead of using mTriggerList.clear(); when updating, do not clear it and add the item to list only if the item does not already exist in the list.
Eg.
for(Trigger trigger: triggerSnapShot...){
if (!mTriggerList.contains(trigger)){
mTriggerList.add(trigger);
}
}
You may need to override the equals method in the Trigger class in order to make the method contains work properly.
I am a beginner, When i add music files to Sd card the list view in my Music app isn't updating untill i reboot the device or my genymotion emulator. and the songs are also playing with lagging.
Here is my main Acivity.java code :
import com.techdsk.musicdsk.musicdsk.adapter.CustomAdapter;
import com.techdsk.musicdsk.musicdsk.controls.Controls;
import com.techdsk.musicdsk.musicdsk.service.SongService;
import com.techdsk.musicdsk.musicdsk.util.MediaItem;
import com.techdsk.musicdsk.musicdsk.util.PlayerConstants;
import com.techdsk.musicdsk.musicdsk.util.UtilFunctions;
public class MainActivity extends Activity {
String LOG_CLASS = "MainActivity";
CustomAdapter customAdapter = null;
static TextView playingSong;
Button btnPlayer;
static Button btnPause, btnPlay, btnNext, btnPrevious;
Button btnStop;
LinearLayout mediaLayout;
static LinearLayout linearLayoutPlayingSong;
ListView mediaListView;
ProgressBar progressBar;
TextView textBufferDuration, textDuration;
static ImageView imageViewAlbumArt;
static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
context = MainActivity.this;
init();
}
private void init() {
getViews();
setListeners();
playingSong.setSelected(true);
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
if(PlayerConstants.SONGS_LIST.size() <= 0){
PlayerConstants.SONGS_LIST = UtilFunctions.listOfSongs(getApplicationContext());
}
setListItems();
}
private void setListItems() {
customAdapter = new CustomAdapter(this,R.layout.custom_list, PlayerConstants.SONGS_LIST);
mediaListView.setAdapter(customAdapter);
mediaListView.setFastScrollEnabled(true);
}
private void getViews() {
playingSong = (TextView) findViewById(R.id.textNowPlaying);
btnPlayer = (Button) findViewById(R.id.btnMusicPlayer);
mediaListView = (ListView) findViewById(R.id.listViewMusic);
mediaLayout = (LinearLayout) findViewById(R.id.linearLayoutMusicList);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
linearLayoutPlayingSong = (LinearLayout) findViewById(R.id.linearLayoutPlayingSong);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnStop = (Button) findViewById(R.id.btnStop);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
imageViewAlbumArt = (ImageView) findViewById(R.id.imageViewAlbumArt);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
}
private void setListeners() {
mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id){
Log.d("TAG", "TAG Tapped INOUT(IN)");
PlayerConstants.SONG_PAUSED = false;
PlayerConstants.SONG_NUMBER = position;
boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
if (!isServiceRunning) {
Intent i = new Intent(getApplicationContext(),SongService.class);
startService(i);
} else {
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage());
}
updateUI();
changeButton();
Log.d("TAG", "TAG Tapped INOUT(OUT)");
}
});
btnPlayer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AudioPlayerActivity.class);
startActivity(i);
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.playControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.pauseControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.nextControl(getApplicationContext());
}
});
btnPrevious.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.previousControl(getApplicationContext());
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SongService.class);
stopService(i);
linearLayoutPlayingSong.setVisibility(View.GONE);
}
});
imageViewAlbumArt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AudioPlayerActivity.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try{
boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}else{
linearLayoutPlayingSong.setVisibility(View.GONE);
}
changeButton();
PlayerConstants.PROGRESSBAR_HANDLER = new Handler(){
#Override
public void handleMessage(Message msg){
Integer i[] = (Integer[])msg.obj;
textBufferDuration.setText(UtilFunctions.getDuration(i[0]));
textDuration.setText(UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}catch(Exception e){}
}
#SuppressWarnings("deprecation")
public static void updateUI() {
try{
MediaItem data = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER);
playingSong.setText(data.getTitle() + " " + data.getArtist() + "-" + data.getAlbum());
Bitmap albumArt = UtilFunctions.getAlbumart(context, data.getAlbumId());
if(albumArt != null){
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(albumArt));
}else{
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(UtilFunctions.getDefaultAlbumArt(context)));
}
linearLayoutPlayingSong.setVisibility(View.VISIBLE);
}catch(Exception e){}
}
public static void changeButton() {
if(PlayerConstants.SONG_PAUSED){
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
}else{
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
public static void changeUI(){
updateUI();
changeButton();
}
}
Here is my Audioplayer Activity.java Code :
package com.techdsk.musicdsk.musicdsk;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.techdsk.musicdsk.musicdsk.controls.Controls;
import com.techdsk.musicdsk.musicdsk.service.SongService;
import com.techdsk.musicdsk.musicdsk.util.PlayerConstants;
import com.techdsk.musicdsk.musicdsk.util.UtilFunctions;
public class AudioPlayerActivity extends Activity {
Button btnBack;
static Button btnPause;
Button btnNext;
static Button btnPlay;
static TextView textNowPlaying;
static TextView textAlbumArtist;
static TextView textComposer;
static LinearLayout linearLayoutPlayer;
ProgressBar progressBar;
static Context context;
TextView textBufferDuration, textDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.audio_player);
context = this;
init();
}
private void init() {
getViews();
setListeners();
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
PlayerConstants.PROGRESSBAR_HANDLER = new Handler(){
#Override
public void handleMessage(Message msg){
Integer i[] = (Integer[])msg.obj;
textBufferDuration.setText(UtilFunctions.getDuration(i[0]));
textDuration.setText(UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}
private void setListeners() {
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.previousControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.pauseControl(getApplicationContext());
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.playControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.nextControl(getApplicationContext());
}
});
}
public static void changeUI(){
updateUI();
changeButton();
}
private void getViews() {
btnBack = (Button) findViewById(R.id.btnBack);
btnPause = (Button) findViewById(R.id.btnPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPlay = (Button) findViewById(R.id.btnPlay);
textNowPlaying = (TextView) findViewById(R.id.textNowPlaying);
linearLayoutPlayer = (LinearLayout) findViewById(R.id.linearLayoutPlayer);
textAlbumArtist = (TextView) findViewById(R.id.textAlbumArtist);
textComposer = (TextView) findViewById(R.id.textComposer);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
textNowPlaying.setSelected(true);
textAlbumArtist.setSelected(true);
}
#Override
protected void onResume() {
super.onResume();
boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}
changeButton();
}
public static void changeButton() {
if(PlayerConstants.SONG_PAUSED){
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
}else{
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
private static void updateUI() {
try{
String songName = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getTitle();
String artist = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getArtist();
String album = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbum();
String composer = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getComposer();
textNowPlaying.setText(songName);
textAlbumArtist.setText(artist + " - " + album);
if(composer != null && composer.length() > 0){
textComposer.setVisibility(View.VISIBLE);
textComposer.setText(composer);
}else{
textComposer.setVisibility(View.GONE);
}
}catch(Exception e){
e.printStackTrace();
}
try{
long albumId = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbumId();
Bitmap albumArt = UtilFunctions.getAlbumart(context, albumId);
if(albumArt != null){
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(albumArt));
}else{
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(UtilFunctions.getDefaultAlbumArt(context)));
}
}catch(Exception e){
e.printStackTrace();
}
}
}
custom adapter .java code :
package com.techdsk.musicdsk.musicdsk.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.techdsk.musicdsk.musicdsk.R;
import com.techdsk.musicdsk.musicdsk.util.MediaItem;
import com.techdsk.musicdsk.musicdsk.util.UtilFunctions;
public class CustomAdapter extends ArrayAdapter<MediaItem>{
ArrayList<MediaItem> listOfSongs;
Context context;
LayoutInflater inflator;
public CustomAdapter(Context context, int resource, ArrayList<MediaItem> listOfSongs) {
super(context, resource, listOfSongs);
this.listOfSongs = listOfSongs;
this.context = context;
inflator = LayoutInflater.from(context);
}
private class ViewHolder{
TextView textViewSongName, textViewArtist, textViewDuration;
}
ViewHolder holder;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView = convertView;
if(convertView == null){
myView = inflator.inflate(R.layout.custom_list, parent, false);
holder = new ViewHolder();
holder.textViewSongName = (TextView) myView.findViewById(R.id.textViewSongName);
holder.textViewArtist = (TextView) myView.findViewById(R.id.textViewArtist);
holder.textViewDuration = (TextView) myView.findViewById(R.id.textViewDuration);
myView.setTag(holder);
}else{
holder = (ViewHolder)myView.getTag();
}
MediaItem detail = listOfSongs.get(position);
holder.textViewSongName.setText(detail.toString());
holder.textViewArtist.setText(detail.getAlbum() + " - " + detail.getArtist());
holder.textViewDuration.setText(UtilFunctions.getDuration(detail.getDuration()));
return myView;
}
}
when you add the file you can use NotifyDatasetChanged(). this will tell your adapter to refresh its data. So when your source array is updated after adding a new file you can call NotifyDatasetChanged() method.
as Ex. if you have a method named Add() inside your adapter then.
public void Add (item e){
items.add (e);
NotifyDatasetChanged();
}
will refresh your data.
Your list is not getting updated because it is not informed about the data change,
the documentation in the ADW explains:
notifyDataSetChanged() Notifies the attached observers that the
underlying data has been changed and any View reflecting the data set
should refresh itself.
Solution
Notify yor adapter:
customAdapter.notifyDataSetChanged();
I have this strange bug in my android app. I have one activity with a recycler view and some items in it (in my case there are school subjects four textViews and one framelayout).
When you click on an item a transition with shared elements will be performed and you enter the EditActivity where you can edit the subject. After the transistion finished the text in the editText got shifted up. The Text becomes normal only when you click the editText, i don't know why. Sometimes the text appears normal. Maybe it is because I make a transition from a textView (in the item) to an editText (in the EditActitvty).
Please advise. This is my code.
SubjectActivity.java with RecyclerView:
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Learn.sdk21()) {
//To enable window content transitions in your code instead, call the Window.requestFeature() method:
getWindow().requestFeature(android.view.Window.FEATURE_CONTENT_TRANSITIONS);
Transition ts_enter = new Explode(); //Slide(); //Explode();
Transition ts_exit = new ChangeBounds();
ts_enter.setDuration(Learn.animationTime);
ts_exit.setDuration(Learn.animationTime);
/*
If you have set an enter transition for the second activity,
the transition is also activated when the activity starts.
*/
getWindow().setEnterTransition(ts_enter);
getWindow().setExitTransition(ts_exit);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject);
//Database
dao = new DAO(getApplicationContext());
subjectList = dao.getAllSubjectsAlphabetical();
//Custom Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitle(R.string.Subject);
recyclerViewSubject = (RecyclerView) findViewById(R.id.recyclerViewSubject);
setRecyclerViewSubject();
//FloatingActionButton
fabAddSubject = (FloatingActionButton)
findViewById(R.id.fabAddSubject);
fabAddSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddSubjectActivity.class));
}
});
fabAddSubject.attachToRecyclerView(recyclerViewSubject);
}
private void setRecyclerViewSubject() {
//RecyclerView
subjectRecyclerViewAdapter =
new SubjectRecyclerViewAdapter(this, dao.getAllSubjectsAlphabetical());
subjectRecyclerViewAdapter.setClickListener(this);
recyclerViewSubject.setLayoutManager(new LinearLayoutManager(this));
recyclerViewSubject.setAdapter(new ScaleInAnimationAdapter(subjectRecyclerViewAdapter));
}
#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_subject, 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 (id == R.id.action_settings) {
return true;
} else if (id == android.R.id.home) {
this.finish();
return true;
} else if (id == R.id.debugDelete) {
try {
deleteAll();
} catch (Exception e) {
System.out.println("--> Tried to delete all but: " + e + "<--");
}
return true;
} else if (id == R.id.debugAdd) {
try {
add();
} catch (Exception e) {
System.out.println("--> Tried to delete add5: " + e + "<--");
}
return true;
} else if (id == R.id.refreshSubjectList) {
subjectList = dao.getAllSubjectsAlphabetical();
subjectRecyclerViewAdapter.dataChange(subjectList);
}
return super.onOptionsItemSelected(item);
}
#Override
public void itemClicked(View v, int postion) {
editSubject(v, postion);
}
private void editSubject(View v, int pos) {
Intent intent = new Intent(getApplicationContext(), EditSubjectActivity.class);
intent.putExtra("subjectPos", pos);
if (Learn.sdk21()) {
View view = findViewById(R.id.buttonColor);
Pair<View, String> p1 = Pair.create(v.findViewById(R.id.frameLayoutSubjectColor),
v.findViewById(R.id.frameLayoutSubjectColor).getTransitionName());
Pair<View, String> p2 = Pair.create(v.findViewById(R.id.textViewSubject),
v.findViewById(R.id.textViewSubject).getTransitionName());
Pair<View, String> p3 = Pair.create(v.findViewById(R.id.textViewShort),
v.findViewById(R.id.textViewShort).getTransitionName());
Pair<View, String> p4 = Pair.create(v.findViewById(R.id.textViewRoom),
v.findViewById(R.id.textViewRoom).getTransitionName());
Pair<View, String> p5 = Pair.create(v.findViewById(R.id.textViewTeacher),
v.findViewById(R.id.textViewTeacher).getTransitionName());
Pair<View, String> p6 = Pair.create(findViewById(R.id.fabAddSubject),
findViewById(R.id.fabAddSubject).getTransitionName());
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(SubjectActivity.this,
p1, p2, p3, p4, p5, p6);
intent.putExtra("SubjectColor", v.findViewById(R.id.frameLayoutSubjectColor).getTransitionName());
intent.putExtra("SubjectName", v.findViewById(R.id.textViewSubject).getTransitionName());
intent.putExtra("SubjectShort", v.findViewById(R.id.textViewShort).getTransitionName());
intent.putExtra("SubjectRoom", v.findViewById(R.id.textViewRoom).getTransitionName());
intent.putExtra("SubjectTeacher", v.findViewById(R.id.textViewTeacher).getTransitionName());
startActivityForResult(intent, 12, options.toBundle());
} else {
startActivityForResult(intent, 12);
}
}
private void add() {
String[] name = {"Deutsch", "Englisch", "Biologie", "Mathe", "Geschichte",
"Musik", "Physik", "Politik", "Informatik", "Religion"};
String[] nameshort = {"Deu", "Eng", "Bio", "Mat", "Gesch",
"Mus", "Phy", "PoWi", "Info", "Reli"};
String[] room = {"A222", "T292", "B322", "M22", "G666",
"A373", "B888", "C938", "I999", "T666"};
String[] t = {"Test1", "Test2", "Test3", "Test4", "Test5",
"Test6", "Test7", "Test8", "Test9", "Test10"};
String[] c = {"#fff200", "#ff0000", "#ff9000", "#00bbff", "#2aff00",
"#0037ff", "#90ff00", "#00ff4c", "#00ffb2", "#4c00ff"};
for (int i = 0; i < name.length; i++) {
Subject subject = new Subject(name[i], nameshort[i], room[i], t[i], Color.parseColor(c[i]));
dao.addSubject(subject);
}
setRecyclerViewSubject();
}
private void deleteAll() {
int oldSize = dao.getAllSubjects().size();
for (int i = (oldSize - 1); i >= 0; i--) {
int id = dao.getAllSubjects().get(i).getId();
dao.deleteSubject(id);
}
subjectRecyclerViewAdapter =
new SubjectRecyclerViewAdapter(getApplicationContext(), dao.getAllSubjectsAlphabetical());
recyclerViewSubject.setAdapter(new ScaleInAnimationAdapter(subjectRecyclerViewAdapter));
recyclerViewSubject.setLayoutManager(new LinearLayoutManager(this));
subjectRecyclerViewAdapter.notifyItemRangeRemoved(0, dao.getAllSubjects().size());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int subId = data.getIntExtra("subjectId", 0);
int subPos = data.getIntExtra("subjectPos", 0);
int subNewPos = data.getIntExtra("subjectNewPos", subPos);
subjectList = dao.getAllSubjectsAlphabetical();
System.out.print("requestCode" + requestCode
+ "\n" +
"resultCode" + resultCode
+ "\n" +
"subId" + subId
+ "\n" +
"subPos" + subPos
+ "\n" +
"subNewPos" + subNewPos);
if (requestCode == 12) {
if (resultCode == 2) {//Edit
subjectRecyclerViewAdapter.updateItem(subjectList, subPos, subNewPos);
recyclerViewSubject.setAdapter(subjectRecyclerViewAdapter);
} else if (resultCode == 3) {//Delete
subjectRecyclerViewAdapter.removeItem(subjectList, subPos);
recyclerViewSubject.setAdapter(subjectRecyclerViewAdapter);
}
}
}
}
EditSubjectActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Learn.sdk21()) {
//To enable window content transitions in your code instead, call the Window.requestFeature() method:
getWindow().requestFeature(android.view.Window.FEATURE_CONTENT_TRANSITIONS);
Transition ts_enter = new Explode(); //Slide(); //Explode();
Transition ts_exit = new ChangeBounds(); //Slide(); //Explode();
ts_enter.setDuration(Learn.animationTime);
ts_exit.setDuration(Learn.animationTime);
getWindow().setEnterTransition(ts_enter);
getWindow().setExitTransition(ts_exit);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_subject);
//Database
dao = new DAO(getApplicationContext());
//Custom Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
buttonColor = (Button) findViewById(R.id.buttonColor);
buttonColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
colorPickerDialog = new ColorPickerDialog(EditSubjectActivity.this, subject.getColor());
colorPickerDialog.setAlphaSliderVisible(false);
colorPickerDialog.setHexValueEnabled(true);
colorPickerDialog.setTitle("Background");
colorPickerDialog.setOnColorChangedListener(new ColorPickerDialog.OnColorChangedListener() {
#Override
public void onColorChanged(int i) {
subject.setColor(i);
buttonColor.setText("#" + Integer.toHexString(subject.getColor()));
buttonColor.setBackgroundColor(i);
}
});
colorPickerDialog.show();
}
});
//EditText
editTextSubject = (EditText) findViewById(R.id.editTextSubject);
editTextShort = (EditText) findViewById(R.id.editTextShort);
editTextRoom = (EditText) findViewById(R.id.editTextRoom);
editTextTeacher = (EditText) findViewById(R.id.editTextTeacher);
//FAB
fabSaveSubject = (FloatingActionButton) findViewById(R.id.fabSaveSubject);
fabSaveSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveSubject();
}
});
fabDeleteSubject = (FloatingActionButton) findViewById(R.id.fabDeleteSubject);
fabDeleteSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteSubject();
}
});
setUp();
if(Learn.sdk21()){
Intent intent = getIntent();
editTextSubject.setTransitionName(intent.getStringExtra("SubjectName"));
editTextShort.setTransitionName(intent.getStringExtra("SubjectShort"));
editTextRoom.setTransitionName(intent.getStringExtra("SubjectRoom"));
editTextTeacher.setTransitionName(intent.getStringExtra("SubjectTeacher"));
buttonColor.setTransitionName(intent.getStringExtra("SubjectColor"));
}
}
#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_add_subject, 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 (id == R.id.action_settings) {
return true;
} else if (id == android.R.id.home) {
finish(1);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish(1);
}
private void saveSubject() {
subject.setSubject(editTextSubject.getText().toString());
subject.setSubjectShort(editTextShort.getText().toString());
subject.setRoom(editTextRoom.getText().toString());
subject.setTeacher(editTextTeacher.getText().toString());
dao.updateSubject(subjectId, subject);
finish(2);
}
private void deleteSubject() {
dao.deleteSubject(subjectId);
finish(3);
}
private void setUp() {
Intent intent = getIntent();
subjectPos = intent.getIntExtra("subjectPos", 0);
subject = dao.getAllSubjectsAlphabetical().get(subjectPos);
subjectId = subject.getId();
editTextSubject.setText(subject.getSubject());
editTextShort.setText(subject.getSubjectShort());
editTextRoom.setText(subject.getRoom());
editTextTeacher.setText(subject.getTeacher());
buttonColor.setText("#" + Integer.toHexString(subject.getColor()));
buttonColor.setBackgroundColor(subject.getColor());
}
private void finish(int i) {
Intent intent = new Intent();
intent.putExtra("subjectPos", subjectPos);
intent.putExtra("subjectId", subjectId);
setResult(i, intent);
switch (i) {
case 1: //Nothing
finishAfterTransition();
break;
case 2: //Edit
int newPos = dao.getSubjectPosition(dao.getAllSubjectsAlphabetical(), subject);
intent.putExtra("subjectNewPos", newPos);
finishAfterTransition();
break;
case 3: //Delete
finish();
break;
}
}
}
SubjectRecyclerViewAdapter.java:
public class SubjectRecyclerViewAdapter
extends RecyclerView.Adapter
<SubjectRecyclerViewAdapter.subjectViewHolder> {
LayoutInflater inflater;
List<Subject> subjectList;
Context context;
ClickListener clickListener;
DAO dao;
public SubjectRecyclerViewAdapter(Context context, List<Subject> subjectList) {
inflater = LayoutInflater.from(context);
this.subjectList = subjectList;
this.context = context;
dao = new DAO(context);
}
#Override
public subjectViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.subject_item, parent, false);
subjectViewHolder holder = new subjectViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(subjectViewHolder holder, int position) {
Subject subject = subjectList.get(position);
holder.textViewSubject.setText(subject.getSubject());
holder.textViewShort.setText(subject.getSubjectShort());
holder.textViewTeacher.setText(subject.getTeacher());
holder.textViewRoom.setText(subject.getRoom());
holder.frameLayoutSubjectColor.setBackgroundColor(subject.getColor());
if (Learn.sdk21()) {
holder.textViewSubject.setTransitionName("SubjectName_"+position);
holder.textViewShort.setTransitionName("SubjectShort_"+position);
holder.textViewTeacher.setTransitionName("SubjectTeacher_"+position);
holder.textViewRoom.setTransitionName("SubjectRoom_"+position);
holder.frameLayoutSubjectColor.setTransitionName("SubjectColor_" + position);
}
}
#Override
public int getItemCount() {
return subjectList.size();
}
public class subjectViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textViewSubject,textViewShort, textViewRoom, textViewTeacher;
FrameLayout frameLayoutSubjectColor;
public subjectViewHolder(View itemView) {
super(itemView);
textViewSubject = (TextView) itemView.findViewById(R.id.textViewSubject);
textViewShort = (TextView) itemView.findViewById(R.id.textViewShort);
textViewRoom = (TextView) itemView.findViewById(R.id.textViewRoom);
textViewTeacher = (TextView) itemView.findViewById(R.id.textViewTeacher);
frameLayoutSubjectColor = (FrameLayout) itemView.findViewById(R.id.frameLayoutSubjectColor);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (clickListener != null) {
clickListener.itemClicked(v, getPosition());
}
}
}
public interface ClickListener {
public void itemClicked(View v, int postion);
}
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
public void removeItem(List<Subject> subjectList, int pos) {
this.subjectList = subjectList;
notifyItemRemoved(pos);
System.out.println("removeItem");
}
public void updateItem(List<Subject> subjectList, int pos, int newPos) {
this.subjectList = subjectList;
notifyItemChanged(pos);
if (pos != newPos) {
notifyItemMoved(pos, newPos);
}
System.out.println("updateItem");
}
public void dataChange(List<Subject> subjectList) {
this.subjectList = subjectList;
notifyDataSetChanged();
System.out.println("dataChange");
}
}