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);
}
}
Related
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;
In my activity i am receiving a game id from previous activity and using this id i am getting list of data from api. The method ("ApiCheats") in activity is used to get lis t of data.
I want to pass this list to my fragment in view pager, for this i used bundle but in fragment the bundle is null.
How should i pass bundle list to fragment , this data i am receiving through retrofit.
This is the Activity
public class GameListCheatsActivity extends AppCompatActivity {
private final String TAG = GameListCheatsActivity.class.getSimpleName();
public List<Cheats> Cheats;
ArrayList cheats = new ArrayList<Cheats>();
// public RecyclerView recyclerView;
String Gameid;
ViewPager viewPager;
ViewPagerAdapter adapter;
TabLayout tabLayout ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_list_cheats);
// recyclerView = (RecyclerView) findViewById(R.id.recycler_id);
// LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.setHasFixedSize(true);
Gameid = getIntent().getStringExtra("GameID");
tabLayout = (TabLayout) findViewById(R.id.tab_layout_id);
viewPager = (ViewPager) findViewById(R.id.viewpager_id);
adapter = new ViewPagerAdapter( getSupportFragmentManager());
ApiCheats();
adapter.AddFragment(new Fragment_Cheats(),"GameCheats");
adapter.AddFragment(new Fragment_Favourites(),"Favourites");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(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) {
if(state == 0){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
if(state == 1){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
}
});
}
public void ApiCheats()
{
ApiUtil.getServiceClass().getAllCheats(Gameid).enqueue(new Callback<List<Cheats>>() {
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("cheatslist", (ArrayList<? extends Parcelable>) Cheats);
Fragment_Cheats fragment_cheats = new Fragment_Cheats();
fragment_cheats.setArguments(bundle);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
#Override
public void onFailure(Call<List<Cheats>> call, Throwable t) {
Log.d(TAG, "error loading from API");
}
});
}
}
this is one of the fragments class
public class Fragment_Cheats extends Fragment {
View v;
private RecyclerView mrecyclerview;
private List<Cheats> lstGameCheats;
public Fragment_Cheats()
{
}
// #Override
// public void onCreate(#Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Bundle bundle = this.getArguments();
// if (bundle != null) {
// lstGameCheats = bundle.getParcelable("cheatslist");
// }
//
// }
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_fragment__cheats, container, false);
mrecyclerview = (RecyclerView)v.findViewById(R.id.recyclerview_cheats);
Bundle bundle = this.getArguments();
if (bundle != null) {
lstGameCheats = bundle.getParcelable("cheatslist");
}
CheatsAdapter recyclerAdapter = new CheatsAdapter(getContext(),lstGameCheats);
mrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mrecyclerview.setAdapter(recyclerAdapter);
return v;
}
}
this is view pager adapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
//return null;
}
#Override
public int getCount() {
return lstTitles.size();
//return 0;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment(Fragment fragment,String title){
lstFragment.add(fragment);
lstTitles.add(title);
}
}
You should set the Cheats to the Fragment which have added to your ViewPagerAdater, but according to your code you just set the data to a new fragment instance.
According to the Fragment_Cheats code, if you want to invoke getArgument() in onCreate() method, you should invoke fragment.setArgument() before the fragment add to the ViewPagerAdapter.
But in your situation it is not possible, because the data get from the network.
So, two step
Set data to the correct Fragment_Cheats instance
Notify Fragment_Cheats data changed, refresh the View state in the fragment
Replace your onResponse()
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Fragment_Cheats fragment_cheats = adapter.getCheatFragment()
fragment_cheats.setDatas(Cheats);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
Fragment_Cheats add setDatas() method
public void setDatas(List<Cheats> datas) {
this.lstGameCheats = datas;
// and set the datas to the RecylerView adapter
recyclerviewAdapter.notifyDataSetChanged();
}
I have a ViewPager in the fragment named FragmentHome, and the viewpager contains fragments. Am using FragmentStatePagerAdapter for this. When the fragmentHome loads first the fragments in Viewpager show perfectly. I have another fragment named FragmentCountryList to select a country, according to that country the fragments in the viewpager to be refreshed/updated. Now The problem is after selecting the country, the country fragment is popped and returns to the FragmentHome, but, there nothing is showing in the view pager, if we scrolls the second page(fragment) can be viewed then scrolls back the first page(fragment) can be viewed.
Am new with the FragmentStatePagerAdapter, so i couldn't rectify the reason for this problem. Please Help. The code i used gives below
public class FragmentHome extends WeGrabBaseFragment {
private static String TAG = "FragmentHome";
private HomeDealsDataClass homeDealsDataClass;//1, homeDealsDataClass2;
private ViewPager viewPagerHome;
private ImageView imgViewDealIndicator;
private OnCitySelectedListener onCitySelectedListener;
private FragPageAdapter fragAdapt;
private ArrayList<HomeDealsDataClass> arrayListHomeData;
private FragmentHomeDetails fragmentHomeDetails1,fragmentHomeDetails2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity = (WeGrabBaseActivity) this.getActivity();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater
.inflate(R.layout.fragment_home, container, false);
((WeGrabMainActivity) Activity).showBottomBar();
((WeGrabMainActivity) Activity).setShowActionBar();
((WeGrabMainActivity) Activity).setHeading(PrefUtil.getCityName(Activity));
((WeGrabMainActivity) Activity).defaultButtonState();
viewPagerHome = (ViewPager) v.findViewById(R.id.viewPagerHome);
viewPagerHome.setOffscreenPageLimit(2);
imgViewDealIndicator = (ImageView) v.findViewById(R.id.imgViewDealIndicator);
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
viewPagerHome.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
} else if (position == 1) {
Picasso.with(Activity).load(R.drawable.deals2).into(imgViewDealIndicator);
}
}
#Override
public void onPageSelected(int position) {
fragAdapt.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
onCitySelectedListener = new OnCitySelectedListener() {
#Override
public void onCitySelected() {
fetchFromWeb();
}
};
fetchFromWeb();
return v;
}
private void fetchFromWeb() {
if (Activity.isNetworkAvailable()) {
if (VolleyUtils.volleyEnabled) {
Activity.startSpinwheel(false, true);
JSONObject jsonObject = new JSONObject();
try {
if (!PrefUtil.isGPSLocation(Activity)) {
jsonObject.putOpt(AppConstants.COUNTRY_ID, PrefUtil.getCountryCode(Activity));
jsonObject.putOpt(AppConstants.CITY_ID, PrefUtil.getCityCode(Activity));
Log.e(TAG, "Not GPS Home : " + jsonObject.toString());
CommandFactory commandFactory = new CommandFactory();
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
} else {
/*jsonObject.putOpt(AppConstants.COUNTRY_NAME, PrefUtil.getCountryName(Activity));
jsonObject.putOpt(AppConstants.CITY_NAME, PrefUtil.getCityName(Activity));*/
jsonObject.putOpt(AppConstants.COUNTRY_ID, "112");
jsonObject.putOpt(AppConstants.CITY_ID, "6");
CommandFactory commandFactory = new CommandFactory();
Log.e(TAG, "In GPS Home : " + jsonObject.toString());
/*commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL_GPS, jsonObject);*/
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onHomeDetailsPageDataLoadedSuccessfully(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedSuccessfully(jsonObject);
Activity.stopSpinWheel();
try {
if (jsonObject != null) {
if (jsonObject != null) {
fragAdapt = new FragPageAdapter(getFragmentManager());
viewPagerHome.setAdapter(fragAdapt);
JSONArray jsonArray = jsonObject.getJSONArray(AppConstants.DEALS);
arrayListHomeData = new ArrayList<HomeDealsDataClass>();
if(jsonArray.length() > 0) {
viewPagerHome.setVisibility(View.VISIBLE);
for (int i = 0; i < jsonArray.length(); i++) {
arrayListHomeData.add(new HomeDealsDataClass(jsonArray.getJSONObject(i)));
}
fragAdapt.notifyDataSetChanged();
}else{
viewPagerHome.setVisibility(View.GONE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onHomeDetailsPageDataLoadedFailed(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedFailed(jsonObject);
Activity.stopSpinWheel();
}
private class FragPageAdapter extends FragmentStatePagerAdapter {
FragPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
Log.e(TAG,"Returns Fragment Home deals 1");
fragmentHomeDetails1 = FragmentHomeDetails.newInstance(arrayListHomeData.get(0));
return fragmentHomeDetails1;
case 1:
Log.e(TAG,"Returns Fragment Home deals 2");
fragmentHomeDetails2 = FragmentHomeDetails.newInstance(arrayListHomeData.get(1));
return fragmentHomeDetails2;
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
if(arrayListHomeData != null)
return arrayListHomeData.size();
else
return 0;
}
}
}
I had this problem too before, after searching through SO answers, this helped me.
Basically try changing your PagerAdapter to extend FragmentStatePagerAdapter from FragmentPagerAdapter
I have some code, but the new HTTPRequest().execute(); won't work. What this code should do is use an HTTP GET request and then display the text on the screen (with the line of code card.setText(mResult);). My entire HTTPRequest class may be wrong? Is there a class that exists that I can call to say something like ExampleHTTPGetClass.getURLData("example.com"); I am fairly new to glass development, here is my code I tried to write:
public class MainActivity extends Activity {
private CardScrollView mCardScroller;
private View mView;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
mView = buildView();
mCardScroller = new CardScrollView(this);
mCardScroller.setAdapter(new CardScrollAdapter() {
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int position) {
return mView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return mView;
}
#Override
public int getPosition(Object item) {
if (mView.equals(item)) {
return 0;
}
return AdapterView.INVALID_POSITION;
}
});
// Handle the TAP event.
mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Plays disallowed sound to indicate that TAP actions are not supported.
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.playSoundEffect(Sounds.DISALLOWED);
}
});
setContentView(mCardScroller);
new HTTPRequest().execute();
}
private View buildView() {
CardBuilder card = new CardBuilder(this, CardBuilder.Layout.TEXT);
card.setText(mResult);
return card.getView();
}
HttpURLConnection mURLConnection;
String mResult;
private class HTTPRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0){
try{
URL url = new URL("http://exampleURL.com");
mURLConnection = (HttpURLConnection)
url.openConnection();
InputStream in = new BufferedInputStream(
mURLConnection.getInputStream());
int ch;
StringBuffer b = new StringBuffer();
while ((ch = in.read()) != -1){
b.append((char) ch);
}
mResult = new String(b);
Log.d("App", mResult);
} catch (Exception e){}
return null;
}
}
}
Thanks, Ryan.
You call buildView() and setText() before executing the Http request. Add onPostExecute in your AsyncTask and setText there. Try this:
private class HTTPRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0){
try{
URL url = new URL("http://exampleURL.com");
mURLConnection = (HttpURLConnection)
url.openConnection();
InputStream in = new BufferedInputStream(
mURLConnection.getInputStream());
int ch;
StringBuffer b = new StringBuffer();
while ((ch = in.read()) != -1){
b.append((char) ch);
}
mResult = new String(b);
Log.d("App", mResult);
} catch (Exception e){}
return null;
}
#Override
protected void onPostExecute(Void v) {
mView = buildView();
}
}
Also, don't forget to add
<uses-permission android:name="android.permission.INTERNET"/>
in the manifest.
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);