I'm taking a picture, but it doesn't display in recyclerview - imageview

I have a screen that when someone click in a button appear a AlertDialog, and user can choose take a picture or choose from gallery. The code of gallery is working good, but the another isn't.
The idea is take a picture and display in a recyclerview.
Bellow I'll post the code:
public class NovoConteudoActivity extends AppCompatActivity{
private RecyclerView recyclerViewAddImage;
private ImageButton buttonAddNewImage;
private List<Imagem> listImagens = new ArrayList<>();
private AdapterImagem adapter;
private Imagem imagemConfigurada;
private ImageView imageDimension;
String currentImagePath = null;
private String[] permissoesNecessarias = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
private static final int SELECAO_CAMERA = 100;
private static final int SELECAO_GALERIA = 200;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_novo_conteudo);
//Inicializar Componentes:
inicalizarComponentes();
//Validar Permissões:
Permissao.validarPermissoes(permissoesNecessarias, this, 1);
//Set Adapter:
adapter = new AdapterImagem(listImagens, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
layoutManager.setStackFromEnd(true);
recyclerViewAddImage.setLayoutManager(layoutManager);
recyclerViewAddImage.setHasFixedSize(true);
recyclerViewAddImage.setAdapter(adapter);
//Evento de clique no Botão para adicionar imagem:
buttonAddNewImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
criarAlertDialog();
}
});
}
#Override
protected void onStart() {
super.onStart();
recyclerViewAddImage.smoothScrollToPosition(listImagens.size());
if (listImagens.size() >= 6){
buttonAddNewImage.setVisibility(View.GONE);
}else {
buttonAddNewImage.setVisibility(View.VISIBLE);
}
}
private void inicalizarComponentes() {
recyclerViewAddImage = findViewById(R.id.recyclerViewAddImage);
buttonAddNewImage = findViewById(R.id.buttonAddNewImage);
imageDimension = findViewById(R.id.imageDimension);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public void criarAlertDialog(){
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Escolha uma opção");
alertDialog.setCancelable(true);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout linearLayoutVertical = new LinearLayout(this);
linearLayoutVertical.setOrientation(LinearLayout.VERTICAL);
linearLayoutVertical.setLayoutParams(params);
TextView textCamera = new TextView(this);
textCamera.setText("Tirar foto");
textCamera.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_photo_camera_black_24dp, 0,0,0);
textCamera.setCompoundDrawablePadding(5);
textCamera.setGravity(Gravity.CENTER_VERTICAL);
textCamera.setLayoutParams(params);
textCamera.setPadding(16,16,10,16);
linearLayoutVertical.addView(textCamera);
TextView textGaleria = new TextView(this);
textGaleria.setText("Escolher Existente...");
textGaleria.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_photo_black_24dp, 0,0,0);
textGaleria.setCompoundDrawablePadding(5);
textGaleria.setGravity(Gravity.CENTER_VERTICAL);
textGaleria.setLayoutParams(params);
textGaleria.setPadding(16,10,10,16);
linearLayoutVertical.addView(textGaleria);
TextView textCancelar = new TextView(this);
textCancelar.setText("Cancelar");
textCancelar.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_close_cinza_24dp, 0,0,0);
textCancelar.setCompoundDrawablePadding(5);
textCancelar.setGravity(Gravity.CENTER_VERTICAL);
textCancelar.setLayoutParams(params);
textCancelar.setPadding(16,10,10,16);
linearLayoutVertical.addView(textCancelar);
alertDialog.setView(linearLayoutVertical);
final AlertDialog dialog = alertDialog.create();
dialog.show();
textCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (i.resolveActivity(getPackageManager()) != null){
File imageFile = null;
try {
imageFile = getImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (imageFile != null){
Uri imageUri = FileProvider.getUriForFile(NovoConteudoActivity.this,
"com.gustavo.android.fileprovider",
imageFile);
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(i, SELECAO_CAMERA);
}
}
dialog.dismiss();
}
});
textGaleria.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (i.resolveActivity(getPackageManager()) != null){
startActivityForResult(i, SELECAO_GALERIA);
}
dialog.dismiss();
}
});
textCancelar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
Bitmap imagem = null;
try {
switch (requestCode){
case SELECAO_CAMERA:
rotateImage(setReducedImageSize());
break;
case SELECAO_GALERIA:
Uri localImagemSelecionada = data.getData();
InputStream imageStream = getContentResolver().openInputStream(localImagemSelecionada);
imagem = BitmapFactory.decodeStream(imageStream);
if (imagem!= null){
imagemConfigurada = new Imagem();
imagemConfigurada.setImagem(imagem);
listImagens.add(imagemConfigurada);
Log.d("Imagem", "onActivityResult: " + listImagens);
adapter.notifyDataSetChanged();
}
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
private File getImageFile()throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
currentImagePath = image.getAbsolutePath();
return image;
}
private Bitmap setReducedImageSize(){
int targetImageViewWidth = imageDimension.getWidth();
int targetImageViewHeight = imageDimension.getHeight();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(currentImagePath, bmOptions);
int cameraImageWidth = bmOptions.outWidth;
int cameraImageHeight = bmOptions.outHeight;
int scaleFactor = Math.min(cameraImageWidth/targetImageViewWidth, cameraImageHeight/targetImageViewHeight);
bmOptions.inSampleSize = scaleFactor;
bmOptions.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(currentImagePath, bmOptions);
}
private void rotateImage(Bitmap bitmap){
ExifInterface exifInterface = null;
try {
exifInterface = new ExifInterface(currentImagePath);
}catch (IOException e){
e.printStackTrace();
}
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Matrix matrix = new Matrix();
switch (orientation){
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(270);
break;
default:
}
Bitmap imageRotate = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
if (imageRotate!= null){
imagemConfigurada = new Imagem();
imagemConfigurada.setImagem(imageRotate);
listImagens.add(imagemConfigurada);
Log.d("Lista", "rotateImage: " + listImagens);
adapter.notifyDataSetChanged();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int permissaoResultado: grantResults){
if (permissaoResultado == PackageManager.PERMISSION_DENIED){
alertaValidacaoPermissao();
}
}
}
private void alertaValidacaoPermissao(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Permissões Negadas");
builder.setMessage("Para utilizar o app é necessário aceitar as permissões");
builder.setCancelable(false);
builder.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
Bellow the code of adapter:
public class AdapterImagem extends RecyclerView.Adapter<AdapterImagem.MyViewHolder> {
List <Imagem> list;
Context context;
public AdapterImagem(List<Imagem> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View item = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_add_photo, parent, false);
return new AdapterImagem.MyViewHolder(item);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Imagem imagem = list.get(position);
Glide
.with(context)
.load(imagem.getImagem())
.centerCrop()
.into(holder.newImagem);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView newImagem;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
newImagem = itemView.findViewById(R.id.newImage);
}
}
}
And the Class Imagem:
public class Imagem {
private Bitmap imagem;
public Imagem() {
}
public Imagem(Bitmap imagem) {
this.imagem = imagem;
}
public Bitmap getImagem() {
return imagem;
}
public void setImagem(Bitmap imagem) {
this.imagem = imagem;
}
}

Because you are setting an adapter with an empty list.
instead of initializing the adapter here:
//don't initialize here
adapter = new AdapterImagem(listImagens, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
.........
instead initialize here:
case SELECAO_GALERIA:
Uri localImagemSelecionada = data.getData();
InputStream imageStream = getContentResolver().openInputStream(localImagemSelecionada);
imagem = BitmapFactory.decodeStream(imageStream);
if (imagem!= null){
imagemConfigurada = new Imagem();
imagemConfigurada.setImagem(imagem);
listImagens.add(imagemConfigurada);
//here
adapter = new AdapterImagem(listImagens,this);
//also set the adapter here
recyclerViewAddImage.setAdapter(adapter);
Log.d("Imagem", "onActivityResult: " + listImagens);
adapter.notifyDataSetChanged();
}
break;

Related

Using FirestoreRecyclerAdapter but phone's screen looks separately

I'm using FirestoreRecyclerAdapter and faced with the problem.
My challenge is that I can add documents and retrieve them the recyclerview but for some reason, thw phone's screen looks separately as attached phone's schreenshot.
how can I do?
Thank You.
This is Adapter;
public MyFriendsAdapter(#NonNull FirestoreRecyclerOptions<ProfileModelClass> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MyFriendsViewholder holder, int position, #NonNull ProfileModelClass model)
{
holder.myNickname.setText(model.getNickname());
holder.myAge.setText(model.getAge());
holder.myGender.setText(model.getGender());
holder.myDistance.setText(model.getDistance());
holder.myUserDescription.setText(model.getUserDescription());
holder.myMarriage.setText(model.getMarriage());
holder.myAddress.setText(model.getAddress());
// String visit_user_id = getSnapshots().getSnapshot(position).getId();
// Intent chatIntent = new Intent(MainActivity.this, ChatActivity.class);
// chatIntent.putExtra("visit_user_id", visit_user_id);
// startActivity(chatIntent);
Glide.with(holder.myProfileImageView.getContext()).load(model.getProfileImage()).into(holder.myProfileImageView);
Glide.with(holder.myPictureOne.getContext()).load(model.getPictureOne()).into(holder.myPictureOne);
Glide.with(holder.myPictureTwo.getContext()).load(model.getPictureTwo()).into(holder.myPictureTwo);
}
#NonNull
#Override
public MyFriendsViewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_friends_list_layout,
parent, false);
return new MyFriendsViewholder(view);
}
class MyFriendsViewholder extends RecyclerView.ViewHolder
{
CircleImageView myProfileImageView;
TextView myNickname,myAge, myGender, myDistance, myUserDescription, myMarriage, myAddress,
myFriendsProfile, SendMessageButton;
ImageView myPictureOne, myPictureTwo;
public MyFriendsViewholder(#NonNull View itemView)
{
super(itemView);
myProfileImageView = itemView.findViewById(R.id.all_friends_profile_image_layout);
myNickname = itemView.findViewById(R.id.all_friends_nickname_layout);
myGender = itemView.findViewById(R.id.all_friends_gender_layout);
myAge = itemView.findViewById(R.id.all_friends_age_layout);
myDistance = itemView.findViewById(R.id.all_friends_distance_layout);
myUserDescription = itemView.findViewById(R.id.all_friends_description_layout);
myMarriage = itemView.findViewById(R.id.all_friends_marriage_layout);
myAddress = itemView.findViewById(R.id.all_friends_address_layout);
myPictureOne = itemView.findViewById(R.id.all_friends_post_image_first);
myPictureTwo = itemView.findViewById(R.id.all_friends_post_image_second);
myFriendsProfile = itemView.findViewById(R.id.all_friends_information_layout);
SendMessageButton = itemView.findViewById(R.id.all_friends_call_layout);
myFriendsProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
itemView.getContext().startActivity(new Intent(itemView.getContext(), ProfileActivity.class));
}
});
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
itemView.getContext().startActivity(new Intent(itemView.getContext(), ChatActivity.class));
}
});
}
This is MainActivity;
private DatabaseReference UsersRef;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference firstUsersProfilesColRef = db.collection("usersProfiles");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestoreList = findViewById(R.id.all_users_list);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("allUsers");
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("홈");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ToolbarProfileBtn = (ImageButton) findViewById(R.id.toolbar_profile_button);
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
ToolbarProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SendUserToSetupActivity();
}
});
DisplayAllUsersList();
}
private void DisplayAllUsersList()
{
Query salaryQuery = firstUsersProfilesColRef;
FirestoreRecyclerOptions<ProfileModelClass> options = new FirestoreRecyclerOptions.Builder<ProfileModelClass>()
.setQuery(salaryQuery, ProfileModelClass.class)
.build();
adapter = new MyFriendsAdapter(options);
mFirestoreList.setHasFixedSize(true);
mFirestoreList.setLayoutManager(new LinearLayoutManager(this));
mFirestoreList.setAdapter(adapter);
}
#Override
protected void onStart()
{
super.onStart();
adapter.startListening();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
This is phone's screenshot;
enter image description here
In your layout file all_friends_list_layout. I think you have used android:layout_height="match_parent"
so there you need to use
android:layout_height="wrap_content"
Or instead of wrap_content you can also use any value like 150dp or whatever you feel appropriate for your need.

Search in Fragments that hold Recyclerview

I have 3 Fragments and they all are holding a recyclerView. But I don't know how I should call adapter.getFilter().filter(newText); in onQueryTextChange. Any ideas?
MainActivity:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
private BottomNavigationView bottomNavigationView;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDB = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----Start Bottom Navigation Bar
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(bottomNavMethod);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new PasswortFragment()).commit();
String id = getResources().getResourceEntryName(bottomNavigationView.getId());
//----End Bottom Navigation Bar
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return true;
}
private BottomNavigationView.OnNavigationItemSelectedListener bottomNavMethod =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch(item.getItemId()){
case R.id.passwoerter:
fragment = new PasswortFragment();
break;
case R.id.bankdaten:
fragment = new BankdatenFragment();
break;
case R.id.kreditkarten:
fragment = new KreditkartenFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
return true;
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment f = MainActivity.this.getSupportFragmentManager().findFragmentById(R.id.container);
if(f instanceof PasswortFragment)
recyclerView = findViewById(R.id.recyclerViewPasswoerter);
if(f instanceof KreditkartenFragment)
recyclerView = findViewById(R.id.recyclerViewKreditkarten);
if(f instanceof BankdatenFragment)
recyclerView = findViewById(R.id.recyclerViewBankdaten);
}
#Override
public boolean onCreateOptionsMenu(#NonNull Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
recyclerView.getAdapter().getFilter().filter(newText); //<--This is not working
return false;
}
});
return true;
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> implements Filterable{
String type;
List<String> dataAll, data1;
Context context;
public Adapter(Context ct, List<String> s1, String typ){
context = ct;
data1 = s1;
type = typ;
dataAll = new ArrayList<>(data1);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.reihen, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.mytext1.setText(data1.get(position));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(type.equals("Passwoerter")){
Intent intent = new Intent(context, DetailsP.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Kreditkarten")){
Intent intent = new Intent(context, DetailsK.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Bankdaten")){
Intent intent = new Intent(context, DetailsB.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return data1.size();
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<String> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0){
filteredList.addAll(dataAll);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(String item: dataAll){
if(item.toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
data1.clear();
data1.addAll( (List) results.values);
notifyDataSetChanged();
}
};
;
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView mytext1;
ConstraintLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mytext1 = itemView.findViewById(R.id.title);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
PasswortFragment (the other two fragments are pretty much the same):
public class PasswortFragment extends Fragment {
public PasswortFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
String tabelle = "Passwort";
List<String> titel;
DatabaseHelper myDB;
Adapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_passwort, container, false);
myDB = new DatabaseHelper(getActivity());
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewPasswoerter);
titel = Arrays.asList(myDB.getItems(tabelle));
final LinearLayoutManager layoutManager = new LinearLayoutManager((getActivity()));
layoutManager.setOrientation((LinearLayoutManager.VERTICAL));
recyclerView.setLayoutManager(layoutManager);
adapter = new Adapter(getActivity(), titel, "Passwoerter");
recyclerView.setAdapter(adapter);
setHasOptionsMenu(true);
return view;
}

Datas repeated in my ListFragment

I encounter a problem with my ListFragment provided by Volley Library and hosted by a ViewPager ! So when i swipe follow Fragment and back to my previous ListFragment, datas are repeated again ! Why ? Please help me !
This my code :
Code for bind ListFragment:
public class AllConferencesFragment extends ListFragment {
// Variables
final String URL_ALL_CONFERENCES = "http://192.168.43.246/android_christEvent/all_events_conference.php";
//final String URL_ALL_CONFERENCES = "http://7avecdieu.org/android_christEvent/all_events_conference.php";
//private static String TAG = ConferenceActivity.class.getSimpleName();
ListView listView;
View view;
List<Event> eventLists = new ArrayList<Event>();
CustomListEventsAdapter customListEventsAdapter;
CircularProgressView circularProgressView;
// Contructeur
public AllConferencesFragment() {
}
// Creation du fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Creation de la vue
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.conferences_frag, container, false);
circularProgressView = (CircularProgressView) view.findViewById(R.id.circular_progress);
return view;
}
// Activité gestionnaire du fragment créé
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
circularProgressView.setVisibility(View.VISIBLE);
circularProgressView.startAnimation();
getListView();
//listView = (ListView) view.findViewById(R.id.list);
customListEventsAdapter = new CustomListEventsAdapter(getActivity(), eventLists);
//listView.setAdapter(customListEventsAdapter);
setListAdapter(customListEventsAdapter);
// On check si la cache est vide
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_ALL_CONFERENCES);
if (entry != null) {
circularProgressView.setVisibility(View.VISIBLE);
// Parcours des données de la cache de cette url passée en parametre
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
else {
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_ALL_CONFERENCES,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Resultats ----> ", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Resultats ----> ", "Error: " + error.getMessage());
//progressBar.setVisibility(View.GONE);
circularProgressView.setVisibility(View.GONE);
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
// Au Cliq sur un iem
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), DetailsEventsActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
}
/**
* Parsing json reponse and passing the data to event view list adapter
**/
private void parseJsonFeed(JSONObject response) {
try {
JSONArray eventArray = response.getJSONArray("events");
for (int i = 0; i < eventArray.length(); i++) {
JSONObject eventObj = (JSONObject) eventArray.get(i);
Event evt = new Event();
evt.setPriceEvent(eventObj.getString("event_price"));
// Image might be null sometimes
String image = eventObj.isNull("event_thumb") ? null : eventObj.getString("event_thumb");
evt.setThumbEvent(image);
evt.setNameEvent(eventObj.getString("event_name"));
evt.setPlaceEvent(eventObj.getString("event_place"));
evt.setHourEvent(eventObj.getString("event_hour"));
evt.setDateEvent(eventObj.getString("event_date"));
eventLists.add(evt);
}
circularProgressView.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
//progressBar.setVisibility(View.GONE);
}
}
Code for Volley Application :
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if(mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// Set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
My parseJsonEvent :
private void parseJsonEvent(JSONObject response) {
try {
JSONArray eventArray = response.getJSONArray(TAG_EVENTS);
// Loop Json node
for (int i = 0; i < eventArray.length(); i++) {
JSONObject eventObj = (JSONObject) eventArray.get(i);
// Create event object
Event evt = new Event();
evt.setIdEvent(eventObj.getInt(TAG_EVENT_ID));
evt.setDateEvent(eventObj.getString(TAG_EVENT_DATE));
evt.setPriceEvent(eventObj.getString(TAG_EVENT_PRICE));
evt.setNameEvent(eventObj.getString(TAG_EVENT_NAME));
evt.setCountryEvent(eventObj.getString(TAG_EVENT_COUNTRY));
evt.setPlaceEvent(eventObj.getString(TAG_EVENT_PLACE));
evt.setTypeEvent(eventObj.getString(TAG_EVENT_TYPE));
// event thumbnail
String eventUrl = eventObj.isNull(TAG_EVENT_THUMB) ? null : eventObj.getString(TAG_EVENT_THUMB);
evt.setThumbEvent(eventUrl);
// Adding in the list object
eventList.add(evt);
// notify list view to adding
}
adapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
}
My Main Activity :
public class ConferenceActivity extends AppCompatActivity {
private Toolbar toolbarConference;
private TabLayout tabLayoutConference;
private ViewPager viewPagerConference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbarConference = (Toolbar) findViewById(R.id.toolbar_conference);
setSupportActionBar(toolbarConference);
viewPagerConference = (ViewPager) findViewById(R.id.viewpager_conference);
setupViewPager(viewPagerConference);
tabLayoutConference = (TabLayout) findViewById(R.id.tabs_conference);
tabLayoutConference.setupWithViewPager(viewPagerConference);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new AllEventsConferenceFragments(), "TOUS");
adapter.addFragment(new ThisWeekFragment(), "AUJOURD'HUI");
adapter.addFragment(new TodayEventFragment(), "CETTE SEMAINE");
adapter.addFragment(new AllEventsConferenceFragments(), "SEMAINE PROCHAINE");
adapter.addFragment(new ThisWeekFragment(), "CE MOIS CI");
adapter.addFragment(new TodayEventFragment(), "MOIS PROCHAIN");
adapter.addFragment(new AllEventsConferenceFragments(), "ANNEE EN COURS");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
public class AllConferencesFragment extends ListFragment {
private boolean loaded = false;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(loaded){
return;
}
loaded = true;
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_ALL_CONFERENCES,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Resultats ----> ", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Resultats ----> ", "Error: " + error.getMessage());
//progressBar.setVisibility(View.GONE);
circularProgressView.setVisibility(View.GONE);
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}

JavaFx - is there any way to refresh whole treeview?

I'm newbie on java fx.
And I'm making an application with treeview and treeview has made by nested set model. So each treeitem has to have left, right data.(I made a treeitem like Treeitem>. Object has data(id, label name, left, right, etc) and String is label name to be shown at treeview.)
The problem is that whole treeitems have to be updated when I add a new treeitem(or delete treeitem). I already implemented whole data(the other treeitem's) to be updated on DB, but treeview still has data isn't updated.
I looked for the way to refresh treeview, but I just found user shouldn't use updateitem forcefully.
Is there any way or method to refresh whole treeview?
FYI. code below
Pair<LabelTreeItem,String> f = new Pair<>(new LabelTreeItem(1, "Root", 0, 0, "",0), "Root");
try {
f = new Pair<>(service.getRoot(), "Root");
} catch (SQLException e) {
System.out.println("Can't find Root Node");
e.printStackTrace();
}
TreeItem<Pair<LabelTreeItem,String>> root = createNode(f);
root.setExpanded(true);
treeView.setRoot(root);
treeView.setEditable(true);
treeView.setCellFactory(new Callback<TreeView<Pair<LabelTreeItem,String>>,TreeCell<Pair<LabelTreeItem,String>>>(){
#Override
public TreeCell<Pair<LabelTreeItem,String>> call(TreeView<Pair<LabelTreeItem,String>> p) {
return new TextFieldTreeCellImpl();
}
});
.....................................
private TreeItem<Pair<LabelTreeItem,String>> createNode(final Pair<LabelTreeItem,String> f) {
return new TreeItem<Pair<LabelTreeItem,String>>(f) {
private boolean isLeaf;
private boolean isFirstTimeChildren = true;
private boolean isFirstTimeLeaf = true;
#Override public ObservableList<TreeItem<Pair<LabelTreeItem,String>>> getChildren() {
if (isFirstTimeChildren) {
isFirstTimeChildren = false;
super.getChildren().setAll(buildChildren(this));
}
return super.getChildren();
}
#Override public boolean isLeaf() {
if (isFirstTimeLeaf) {
isFirstTimeLeaf = false;
Pair<LabelTreeItem,String> f = getValue();
int nodeLeft = f.getKey().getLeft();
int nodeRight = f.getKey().getRight();
if(nodeRight-nodeLeft == 1) {
isLeaf = true;
System.out.println("this is leaf");
}
}
return isLeaf;
}
private ObservableList<TreeItem<Pair<LabelTreeItem,String>>> buildChildren(TreeItem<Pair<LabelTreeItem,String>> TreeItem) {
Pair<LabelTreeItem,String> f = TreeItem.getValue();
System.out.println("ID: "+f.getKey().getId());
int nodeLeft = f.getKey().getLeft();
int nodeRight = f.getKey().getRight();
try {
if (f != null && nodeRight-nodeLeft != 1) {
ArrayList<LabelTreeItem> item = new ArrayList<>();
item = service.getChildren(f.getKey().getLeft(), f.getKey().getRight(), f.getKey().getDepth());
ArrayList<Pair<LabelTreeItem,String>> itemList = new ArrayList<>();
for(int i=0; i<item.size(); i++) {
System.out.println("test : " + item.get(i).getLabel());
Pair<LabelTreeItem,String> pair = createPair(item.get(i), item.get(i).getLabel());
itemList.add(pair);
}
if(itemList.size() != 0) {
ObservableList<TreeItem<Pair<LabelTreeItem,String>>> children = FXCollections.observableArrayList();
for (Pair<LabelTreeItem,String> childNode : itemList) {
children.add(createNode(childNode));
}
return children;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return FXCollections.emptyObservableList();
}
};
}
private Pair<LabelTreeItem, String> createPair(LabelTreeItem item, String name) {
return new Pair<>(item, name);
}
LabelTreeItem.java
public class LabelTreeItem {
private int id;
private String label;
private int left;
private int right;
private String comment;
private int depth;
public LabelTreeItem(int id, String label, int left, int right, String comment, int depth) {
this.id = id;
this.label = label;
this.left = left;
this.right = right;
this.comment = comment;
this.depth = depth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public int getLeft() {
return left;
}
public void setLeft(int left) {
this.left = left;
}
public int getRight() {
return right;
}
public void setRight(int right) {
this.right = right;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
}
TextFieldTreeCellImpl.java
public TextFieldTreeCellImpl() {
service = SqliteService.getInstance();
MenuItem addLabel = new MenuItem("Label add");
addMenu.getItems().add(addLabel);
addLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
getTreeItem().setExpanded(true);
LabelTreeItem newItem = null;
try {
id = getTreeItem().getValue().getKey().getId();
label = getTreeItem().getValue().getKey().getLabel();
depth = getTreeItem().getValue().getKey().getDepth()+1;
left = getTreeItem().getValue().getKey().getLeft();
right = getTreeItem().getValue().getKey().getRight();
newItem = service.getData("New Label", id,depth);
TreeItem<Pair<LabelTreeItem,String>> newLabel = new TreeItem(createPair(newItem, newItem.getLabel()));
getTreeItem().getChildren().add(newLabel);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
MenuItem editLabel = new MenuItem("Label modify");
addMenu.getItems().add(editLabel);
editLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
startEdit();
}
});
MenuItem removeLabel = new MenuItem("Label delete");
addMenu.getItems().add(removeLabel);
removeLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
left = getTreeItem().getValue().getKey().getLeft();
right = getTreeItem().getValue().getKey().getRight();
service.deleteData(left, right, (right-left)+1);
} catch (SQLException e) {
e.printStackTrace();
}
getTreeItem().getParent().getChildren().remove(getTreeItem());
System.out.println("Remove");
}
});
}
#Override
protected void updateItem(final Pair<LabelTreeItem, String> pair, boolean empty) {
super.updateItem(pair, empty);
if (!empty && pair != null) {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(pair.getKey().getLabel());
setGraphic(getTreeItem().getGraphic());
setContextMenu(addMenu);
}
} else {
setText(null);
setGraphic(null);
}
setOnMouseExited(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(pair !=null){
Tooltip tTip = new Tooltip(pair.getKey().getLabel());
tTip.uninstall(getTreeView(), tTip);
}
}
});
setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(pair !=null){
Tooltip tTip = new Tooltip();
tTip.setText(pair.getKey().getLabel()
+"\nComment : "+pair.getKey().getComment()
+"\nLeft : "+pair.getKey().getLeft()
+"\nRight : "+pair.getKey().getRight());
tTip.setFont(new Font("Arial", 16));
tTip.setStyle("-fx-background-color: grey;");
tTip.centerOnScreen();
tTip.install(getTreeView(), tTip);
}
}
});
}
DB Table
id|label|left|right|comment|depth

Trying to implement swipe movement

public class CoursesActivity extends SherlockFragmentActivity {
ArrayList<CourseData> mCoursesList = new ArrayList<CourseData>();
public CoursesListAdapter coursesListAdapter;
public ListView mList;
public AlertDialog.Builder dlgAlert;
public Dialog loginDialog;
public Dialog loginDialogOverflow;
LinearLayout progressBar;
static SQLiteWebcourse dbHelper;
private GestureDetectorCompat mDetector;
public final static String EXTRA_MESSAGE = "com.technion.coolie.webcourse.MESSAGE";
public CoursesActivity() {
dbHelper = new SQLiteWebcourse(this, "WebcoureDB", null, 1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create list of courses
mCoursesList = new ArrayList<CourseData>();
setContentView(R.layout.web_activity_courses);
mList = (ListView) findViewById(R.id.courses_list);
dlgAlert = new AlertDialog.Builder(getApplicationContext());
if (!CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
loginDialog = CoolieAccount.WEBCOURSE.openSigninDialog(this);
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// Check if connection success
if (CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
// Connection SUCCESS
progressBar = (LinearLayout) findViewById(R.id.progressBarLayout_courses);
progressBar.setVisibility(View.VISIBLE);
asyncParse<CourseData> a = new asyncParse<CourseData>() {
#Override
protected List<CourseData> doInBackground(
String... params) {
// TODO Auto-generated method stub
try {
courseList crL = new courseList(
getApplicationContext());
crL.getCourses(CoolieAccount.WEBCOURSE
.getUsername(),
CoolieAccount.WEBCOURSE
.getPassword());
mCoursesList = dbHelper
.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doInBackground(params);
}
#Override
protected void onPostExecute(List<CourseData> result) {
// TODO Auto-generated method stub
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
progressBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
}
};
a.execute("");
} else {
// Connection FAILED
Log.v("dbAss", "Second Time");
}
}
};
loginDialog.setOnDismissListener(dismissListener);
} else {
mCoursesList = dbHelper.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
}
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
// OnItemClickListener itemClicked = new OnItemClickListener() {
//
// #Override
// public void onItemClick(AdapterView<?> list, View view,
// int position, long id) {
// // TODO Auto-generated method stub
// loadCourseInformationActivity(((CourseData) mList
// .getItemAtPosition(position)).CourseDescription);
// }
// };
// mList.setOnItemClickListener(itemClicked);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
this.mDetector.onTouchEvent(event);
// Be sure to call the superclass implementation
return super.onTouchEvent(event);
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.v(DEBUG_TAG,
"onFling: " + event1.toString() + event2.toString());
Toast.makeText(getApplicationContext(), "SWIPED", Toast.LENGTH_LONG)
.show();
if (event2.getX() - event1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
Toast.makeText(getApplicationContext(), "SWIPED",
Toast.LENGTH_LONG).show();
// if (showDeleteButton(e1))
// return true;
return super.onFling(event1, event2, velocityX, velocityY);
}
}
}
Hey fellas, i'm trying to implement swipe detection I went through android lesson and did exactly what is written there: http://developer.android.com/training/gestures/detector.html
For some reason when I touch the screen it doesnt go to onTouchEvent. What seems to be the problem?
You haven't set the touch listener to your ListView.
listView.setOnTouchListener(this);

Resources