ViewPager shows the last images until the new images is not loading - android

My problem:At first time when i open item screen then the all images will be loaded into viewpager after that when i open new item screen then it is showing the old images untill the new images is not loading.
So i want to clear the old images on viewpager when i open a new item.
how can i clear the last images when i open new item screen?
i have written following code for display images in viewpager:
class productimages extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
imageUlrList.clear();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", arg[0]));
JSONObject json = jParser.makeHttpRequest(url, "GET",
params);
try {
int success;
success = json.getInt(TAG_IMAGESUCCESS);
if (success == 1) {
JSONArray productObj = json.getJSONArray(TAG_PIMAGES);
for (int index = 0; index < productObj.length(); index++) {
JSONObject product = productObj.getJSONObject(index);
imageurl = product.getString(TAG_IMAGEURL);
imageUlrList.add(imageurl);
}
} else {
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
try {
mViewPager.setAdapter(null);
mViewSlidingImageAdapter = new ViewSlidingImageAdapter(
getSupportFragmentManager());
mViewPager.setAdapter(mViewSlidingImageAdapter);
mViewSlidingImageAdapter.notifyDataSetChanged();
} catch (Exception e) {
}
}
}
My adapter class:
class ViewSlidingImageAdapter extends FragmentStatePagerAdapter {
public ViewSlidingImageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return imageUlrList.size();
}
#Override
public Fragment getItem(int position) {
return ViewSlidingImage.newInstance(position, product_url);
}
}
ViewSlidingImage:
public class ViewSlidingImage extends Fragment {
private String postionOfArray = "";
static ViewSlidingImage newInstance(int imageNum, String imagePathName) {
final ViewSlidingImage f = new ViewSlidingImage();
final Bundle args = new Bundle();
args.putString("postionOfArray", "" + imageNum);
f.setArguments(args);
return f;
}
public ViewSlidingImage() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
postionOfArray = getArguments().getString("postionOfArray");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.view_sliding_image, container,
false);
ImageView mImageView = (ImageView) v
.findViewById(R.id.tutorial_imageview);
try {
String imagePath = SingleProductscreen.imageUlrList.get(Integer
.parseInt(postionOfArray));
UrlImageViewHelper.setUrlDrawable(mImageView, imagePath);
} catch (Exception e) {
// TODO: handle exception
}
return v;
}
}

ViewSlidingImage loads the ImageView with the contents in the imageUrlList as below:
String imagePath = SingleProductscreen.imageUlrList.get(Integer.parseInt(postionOfArray));
So all you need to do is clear this SingleProductscreen.imageUlrList in the onPreExecute. This way you can make sure that once you call the productimages asynctask, the SingleProductscreen.imageUlrList is empty and hence there wont be any image to load and it will be blank.
protected void onPreExecute() {
super.onPreExecute();
SingleProductscreen.imageUlrList.clear();
mViewSlidingImageAdapter = new ViewSlidingImageAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mViewSlidingImageAdapter);
mViewSlidingImageAdapter.notifyDataSetChanged();
}

Related

Empty Bundle in the onSaveInstanceState method

I display pictures from moviesdb using volley in a gridview. The next step is have that gridview in the landscape mode too. So my logic behind this,is to store the list that contains the data as key value pair inside the onSaveInstantState method as:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("movies", moviesList);
outState.putStringArrayList("images", images);
Log.v("TAG","list size:" + moviesList.size());
}
The log output gives me a size of 20 which is correct. However when I am using the debugger, the line
outState.putParcelableArrayList("movies", moviesList);
gives me an empty bundle. That's very strange! The images list works fine,and can see what's in there. Any ideas what is wrong?
Here is my code.
public class MainFragment extends Fragment {
String BASE_URL = "http://api.themoviedb.org/3/discover/movie?api_key=my_key";
static public ArrayList<Movie> moviesList;
static public ArrayList<String> images;
static public MovieAdapter movieAdapter;
public static String imageIcon;
ImageView imageView;
static public String lastSortOrder;
static GridView gridview;
public MainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null) {
moviesList = savedInstanceState.getParcelableArrayList("movies");
images = savedInstanceState.getStringArrayList("images");
}else{
moviesList = new ArrayList<>();
images = new ArrayList<>();
movieAdapter = new MovieAdapter(getActivity());
updateMovies();
}
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
moviesList = new ArrayList<>();
images = new ArrayList<>();
gridview = (GridView) rootView.findViewById(R.id.gridview);
int ot = getResources().getConfiguration().orientation;
gridview.setNumColumns(ot == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2);
gridview.setAdapter(movieAdapter);
return rootView;
}
private void updateMovies(){
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
BASE_URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray moviesArray = response.getJSONArray("results");
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject movie = moviesArray.getJSONObject(i);
Movie movieItem = new Movie();
movieItem.setTitle(movie.getString("title"));
movieItem.setId(movie.getInt("id"));
movieItem.setBackdrop_path(movie.getString("backdrop_path"));
movieItem.setOriginal_title(movie.getString("original_title"));
movieItem.setOriginal_language(movie.getString("original_language"));
if (movie.getString("overview") == "null") {
movieItem.setOverview("No Overview was Found");
} else {
movieItem.setOverview(movie.getString("overview"));
}
if (movie.getString("release_date") == "null") {
movieItem.setRelease_date("Unknown Release Date");
} else {
movieItem.setRelease_date(movie.getString("release_date"));
}
movieItem.setPopularity(movie.getString("popularity"));
movieItem.setVote_average(movie.getString("vote_average"));
movieItem.setPoster_path(movie.getString("poster_path"));
if (movie.getString("poster_path") == "null") {
movieItem.setPoster_path(API.IMAGE_NOT_FOUND);
} else {
images.add(API.IMAGE_URL + API.IMAGE_SIZE_185 + movie.getString("poster_path"));
}
moviesList.add(movieItem);
Log.v("TAG","list size:" + moviesList.size());
movieAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("movies", moviesList);
outState.putStringArrayList("images", images);
//Log.v("TAG","list size:" + moviesList.size());
}
}
Thanks,
Theo.

set text value from fragment.newInstance String

I am trying to set a string to a textview but everytime i click the button Quiz the activity is just refreshing instead going to fragment activity.
This summarize the situation.
I have dynamic viewPager inside activity called Quiz_Container
Use only one fragment(Module_Topics_Content_Quiz) in public Fragment getItem(int position) or FragmentStatePagerAdapter.
I want to change text of a textview in the fragment from activity everytime i swipe.
I am passing the string using newInstance with parameter from activity to fragment
The string came from quizQuestion.get(position)
I'm getting the right value with the Log.d but when setting it to textview the activity is just refreshing.
this is my code.
Quiz_Container.java
public class Quiz_Container extends AppCompatActivity implements Module_Topics_Content_Quiz.OnFragmentInteractionListener {
android.support.v7.app.ActionBar actionBar;
ViewPager quizPager;
private int topicID;
private int moduleID;
private int subModuleID;
private ArrayList<Integer> quizID;
private ArrayList<String> quizQuestion;
private ArrayList<String> choiceA;
private ArrayList<String> choiceB;
private ArrayList<String> choiceC;
private ArrayList<String> choiceD;
private ArrayList<String> quizAnswer;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz__container);
actionBar = getSupportActionBar();
actionBar.setTitle("Quiz");
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f1ad1e")));
Bundle extras = getIntent().getExtras();
topicID = extras.getInt("topicID");
moduleID = extras.getInt("moduleID");
subModuleID = extras.getInt("subModuleID");
Log.d("quizTopicID", "" + topicID);
Log.d("quizModuleID", "" + moduleID);
Log.d("quizSubModuleID", "" + subModuleID);
new quizTask().execute();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
} // Check Internet Connection
class quizTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
try {
URL quizURL = new URL("http://192.168.1.110/science/index.php/users/get_quiz_items/" + topicID + "/" + moduleID + "/" + subModuleID + "" );
HttpURLConnection con = (HttpURLConnection)quizURL.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String quizResponse;
while ((quizResponse = reader.readLine()) != null) {
return quizResponse;
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
#Override
protected void onPostExecute(String quizResponses) {
Log.d("quizResponse", "" + quizResponses);
try {
JSONObject quizObject = new JSONObject(quizResponses);
boolean result = quizObject.getBoolean("success");
if (result) {
JSONArray quizArray = quizObject.getJSONArray("data");
quizID = new ArrayList<>();
quizQuestion = new ArrayList<>();
choiceA = new ArrayList<>();
choiceB = new ArrayList<>();
choiceC = new ArrayList<>();
choiceD = new ArrayList<>();
quizAnswer = new ArrayList<>();
for (int i = 0; i < quizArray.length(); i ++) {
JSONObject dataQuiz = quizArray.getJSONObject(i);
quizID.add(dataQuiz.getInt("id"));
quizQuestion.add(dataQuiz.getString("question"));
choiceA.add(dataQuiz.getString("a"));
choiceB.add(dataQuiz.getString("b"));
choiceC.add(dataQuiz.getString("c"));
choiceD.add(dataQuiz.getString("d"));
quizAnswer.add(dataQuiz.getString("answer"));
}
Log.d("quizSize", "" + quizID.size());
quizPager = (ViewPager) findViewById(R.id.quizPager);
fragmentManager = Quiz_Container.this.getSupportFragmentManager();
quizPager.setAdapter(new quizAdapter(getSupportFragmentManager()));
quizPager.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) {
}
});
}
else {
Toast.makeText(getApplication(), "no quiz yet", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} // end of quizTask
class quizAdapter extends FragmentStatePagerAdapter {
public quizAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
for (int i = 0; i < quizID.size; i++) {
if (i == position) {
fragment = Module_Topics_Content_Quiz.newInstance(quizQuestion.get(position));
Log.d("testQuestion", "" + quizQuestion.get(position)); // this code is working
}
}
return fragment;
}
#Override
public int getCount() {
return quizID.size();
}
}
}
Module_Topics_Content_Quiz.java
public class Module_Topics_Content_Quiz extends Fragment {
TextView textQuizQuestion;
private String qQuestion;
public Module_Topics_Content_Quiz() {
// Required empty public constructor
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public static Module_Topics_Content_Quiz newInstance(String question) {
Module_Topics_Content_Quiz fragment = new Module_Topics_Content_Quiz();
Bundle args = new Bundle();
args.putString("question", question);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
qQuestion = getArguments().getString("question");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
textQuizQuestion = (TextView) getActivity().findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
// textQuizQuestion.setText(qQuestion); // error if enable
return rootView;
}
}
Please help. Thank you.
In your fragment, try inflating the TextView using the View returned rather than using getActivity()
You need to inflate the Fragment's view and call findViewById() on the View it returns.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
// inflate the View inside Fragment using the View returned
textQuizQuestion = (TextView) rootView.findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
textQuizQuestion.setText(qQuestion);
return rootView;
}
You can also use getView() from within the Fragment to get the root view.
If you wanna call from the enclosing Activity, use
getFragmentManager().findFragmentById(R.id.your_fragment_id).getView().findViewById(R.id.your_view);

Listview items reloaded on fragment

In my app there is a fragment class (TabFragmentComerTiposRestaurante). It has also two tab fragments in it (Case 0: PrimaryFragmentComerTiposRestaurante, Case 1: SocialFragmentComerTiposRestaurante).
On both fragment classes there is a listview. When clicking on an item from this list, another fragment class is shown (PrimaryFragmentComer.
Shorty this the schema:
TabFragmentComerTiposRestaurante(#F1)
-[PrimaryFragmenComerTiposRestaurante](#F11)--[PrimaryFragmentComer](#F111)
-[SocialFragmentComerTiposRestaurante](#F12)--[SocialFragmentComer](#F121)
The issue I need to solve is the following:
If at (#F111) or at (#F121) the users click on the back button, then the listview items from #F11 and #F12 are loaded again. That means, if on the first #F11 call there is an item called "Cocina americana", then going back from #F111 to #F11 or going back from #F121 to #F12, there are now two equal items: First row=Cocina americana, Second row=Cocina americana. And that happens every time the user goes from #F11 or #F12 to #F111 or #F112.
Here you can find the code for
F1:
public class TabFragmentComerTiposRestaurante extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout_tipo_rte,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragmentComerTiposRestaurante();
case 1 : return new SocialFragmentComerTiposRestaurante();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "CIUDAD JUAREZ";
case 1 :
return "EL PASO";
}
return null;
}
}
}
Code for #F11
public class PrimaryFragmentComerTiposRestaurante extends Fragment implements AdapterView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "..hiddene here";
private ProgressDialog pDialog;
private List<TipoRestaurante> tipoRestauranteList = new ArrayList<TipoRestaurante>();
private ListView listView;
private CustomListAdapterTipoRte adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_tiporte, null);
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapterTipoRte (getActivity(), tipoRestauranteList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Procesando tipos..");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
Log.d("estoy aqui","estoy");
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
TipoRestaurante restaurante = new TipoRestaurante();
restaurante.setId_tipo(obj.getInt("id_tipo"));
restaurante.setNombre_tipo(obj.getString("nombre_tipo"));
restaurante.setFoto_tipo(obj.getString("foto_tipo"));
Log.d(TAG, response.toString());
// adding movie to movies array
tipoRestauranteList.add(restaurante);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(obj.optString("id_tipo"));
// pDialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TipoRestaurante rteActual = (TipoRestaurante) adapter.getItem(position);
String msg = "Has elegido el tipo " + rteActual.getNombre_tipo();
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Fragment newFragment = new PrimaryFragmentComer();
Bundle args = new Bundle();
args.putInt("myIntLabel", 2);
args.putString("myStringLabel", rteActual.getNombre_tipo());
//and you can add all you want to that bundle like this
newFragment.setArguments(args);
if (mListener != null) {
mListener.onFragmentInteraction(newFragment);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Fragment fragment);
}
}
And now code for #F111:
public class PrimaryFragmentComer extends Fragment implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "...hidden here";
private ProgressDialog pDialog;
private List<Restaurante> restauranteList = new ArrayList<Restaurante>();
private ListView listView;
private CustomListAdapterRte adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_comer, null);
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
Bundle args = getArguments();
String hola = args.getString("myStringLabel");
Log.d("TIPO RTE", hola);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapterRte (getActivity(), restauranteList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Procesando restaurantes...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url+hola,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Restaurante restaurante = new Restaurante();
restaurante.setId_rte(obj.getInt("id_rte"));
restaurante.setNombre(obj.getString("nombre_rte"));
restaurante.setDescripcion(obj.getString("descripcion_rte"));
restaurante.setLatitud(obj.getDouble("latitud_rte"));
restaurante.setLongitud(obj.getDouble("longitud_rte"));
restaurante.setDireccion(obj.getString("direccion_rte"));
restaurante.setWeb(obj.getString("web_rte"));
restaurante.setTel_rte(obj.getString("tel_rte"));
restaurante.setTel_reservas(obj.getString("tel_reservas"));
restaurante.setFoto(obj.getString("foto_rte"));
restaurante.setCalificacion(obj.getDouble("calificacion_rte"));
restaurante.setTipo_rte(obj.getString("tipo_rte"));
restaurante.setFacebook(obj.getString("facebook_rte"));
restaurante.setTwitter(obj.getString("google_rte"));
restaurante.setZona(obj.getString("zona_rte"));
restaurante.setCiudad(obj.getInt("ciudad"));
restaurante.setPoi(obj.getInt("poi"));
// adding movie to movies array
restauranteList.add(restaurante);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(obj.optString("id_rte"));
// pDialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Restaurante rteActual = (Restaurante) adapter.getItem(position);
String msg = "Elegiste el restaurante " + rteActual.getNombre();
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), Detalle_Restaurante.class);
intent.putExtra("id_rte", rteActual.getId_rte());
intent.putExtra("nombre_rte", rteActual.getNombre());
intent.putExtra("descripcion_rte", rteActual.getDescripcion());
intent.putExtra("latitud_rte", rteActual.getLatitud());
intent.putExtra("longitud_rte", rteActual.getLongitud());
intent.putExtra("direccion_rte", rteActual.getDireccion());
intent.putExtra("web_rte", rteActual.getWeb());
intent.putExtra("tel_rte", rteActual.getTel_rte());
intent.putExtra("tel_reservas", rteActual.getTel_reservas());
intent.putExtra("foto_rte", rteActual.getFoto());
intent.putExtra("calificacion_rte", rteActual.getCalificacion());
intent.putExtra("tipo_rte", rteActual.getTipo_rte());
intent.putExtra("facebook_rte", rteActual.getFacebook());
intent.putExtra("google_rte", rteActual.getTwitter());
intent.putExtra("zona_rte", rteActual.getZona());
intent.putExtra("ciudad_rte", rteActual.getCiudad());
intent.putExtra("poi_rte", rteActual.getPoi());
startActivity(intent);
}
}
As mentioned in the comment,
Data is being readded to tipoRestauranteList in your onResponse() method so to avoid that write tipoRestauranteList.clear() after hidePDialog().
Same will be happening in your #F12. Doing this you can rectify the same. :)

android progressdialog not showing in gallery setOnItemSelectedListener method

i parsed json and i can show my json'components in gallery,with paseadapter.
also i have setOnItemSelectedListener method,int this method i changed background image by position and also i have thread in this method (1000 milliseconds) and progressdialog. and somethimes when i click my listview i have nullpoint exception .progressdialog is my problem
this is a my source
public class MainmoviesList extends Fragment {
public final static String TAG = MainmoviesList.class.getSimpleName();
String imageurl = "******";
public static List<ServerItems> arrayOfList;
public static Gallery main_listview;
private AzercellMainPageAdapter objAdapter;
private RelativeLayout mSwitcher;
private CustomerStatistic cs;
private String apisha_url = "*********";
public static int mPosition;
private ServerItems objItem;
public static MainmoviesList newInstance() {
return new MainmoviesList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_movies_list, container,
false);
mSwitcher = (RelativeLayout) rootView.findViewById(R.id.rootNode);
main_listview = (Gallery) rootView
.findViewById(R.id.horizontallistview);
arrayOfList = new ArrayList<ServerItems>();
cs = new CustomerStatistic();
cs.execute(apisha_url);
main_listview.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
mPosition = position;
final ProgressDialog ringProgressDialog = ProgressDialog.show(
getActivity(), "Please wait ...",
"Downloading Image ...", true);
ringProgressDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
loadimagePosition(mPosition);
Thread.sleep(1000);
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
main_listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mPosition = position;
MoviewListResult newFragment = new MoviewListResult();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
Bundle bundle = new Bundle();
bundle.putString("image", arrayOfList.get(position)
.getBlurimage());
bundle.putString("title", arrayOfList.get(position).getTitle());
bundle.putString("trailer", arrayOfList.get(position)
.getYoutube());
bundle.putString("category", arrayOfList.get(position)
.getCategory());
bundle.putString("writer", arrayOfList.get(position)
.getWritten());
bundle.putString("stars", arrayOfList.get(position).getStars());
bundle.putString("descraption", arrayOfList.get(position)
.getDescraption());
bundle.putString("time", arrayOfList.get(position).getTime());
newFragment.setArguments(bundle);
transaction.replace(R.id.content_frame, newFragment);
transaction.commit();
}
});
return rootView;
}
private class CustomerStatistic extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.show();
pDialog.setContentView(R.layout.custom_progressdialog);
}
#Override
protected String doInBackground(String... params) {
return Utils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray mainJson = new JSONArray(result);
for (int i = 0; i < mainJson.length(); i++) {
JSONObject objJson = mainJson.getJSONObject(i);
objItem = new ServerItems();
objItem.setImage(imageurl + objJson.getString("ipone_4"));
objItem.setTitle(objJson.getString("title"));
objItem.setYoutube(objJson.getString("youtube"));
objItem.setWritten(objJson.getString("written"));
objItem.setCategory(objJson.getString("category"));
objItem.setDescraption(objJson.getString("descraption"));
objItem.setStars(objJson.getString("stars"));
objItem.setBlurimage(imageurl
+ objJson.getString("ipone_4_blur"));
JSONObject cinema = objJson.getJSONObject("Cinemas");
JSONArray cinemasarray = cinema.getJSONArray("Cinemaname");
for (int j = 0; j < cinemasarray.length(); j++) {
JSONObject objJson1 = cinemasarray.getJSONObject(j);
JSONArray info = objJson1.getJSONArray("info");
for (int k = 0; k < info.length(); k++) {
JSONObject information = info.getJSONObject(k);
objItem.setTime(information.getString("time"));
Log.e("time is", objItem.getTime());
}
}
arrayOfList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
setAdapterToListview();
}
}
public void setAdapterToListview() {
objAdapter = new AzercellMainPageAdapter(getActivity(),
R.layout.azercell_main_page_adapter, arrayOfList);
main_listview.setAdapter(objAdapter);
}
public void loadimagePosition(int pos) {
URL url;
try {
url = new URL(arrayOfList.get(pos).getBlurimage());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Drawable drawable = new BitmapDrawable(bmp);
mSwitcher.setBackgroundDrawable(drawable);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is a my log cat error
what am i doing wrong? if anyone knows solution please help me
thanks
A quick google search `android nullpointerexception resolve dialog theme``gave me this:
NullPointerException when creating a new Dialog
Remember to upvote his answer as well if it helps.
Also why do you want to sleep in your thread? You are aware that it is not doing any computation while sleeping, right?
I would create an AsyncTask for that aswell, you obviously know how to use it. Then you can also show the progress dialog in onPreExecute and dismiss it in onPostExecute. Much cleaner in my opinion.

implement AsyncTask in Fragment android

I've an activity which output json data from as a list. But now I want to implement it in a fragment.
In this fragment I want to view it as gridview. And both files works fine. but when I tried to implement AsyncTask I gets several redflags as unreachable code. Can someone help me with this please?
Edited: New
public class SalesFragment extends Fragment {
GridView gridView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View gv = inflater.inflate(R.layout.hot_sales, null);
gridView = (GridView) gv.findViewById(R.id.grid_view);
bindGridview();
return gv;
}
public void bindGridview() {
new MyAsyncTask(getActivity(),gridView).execute("");
}
class MyAsyncTask extends AsyncTask<String, String, String> {
GridView mGridView;
Activity mContext;
Response response;
public MyAsyncTask(Activity context,GridView gview) {
this.mGridView=gview;
this.mContext=context;
}
protected String doInBackground(String... params) {
File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/sample.txt");
if(file.exists()) {
try{
Reader inputStreamReader = new InputStreamReader(new FileInputStream(file));
Gson gson = new Gson();
this.response = gson.fromJson(inputStreamReader, Response.class);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (#SuppressWarnings("hiding") IOException e){
e.printStackTrace();
}
}else{
System.out.println("Error");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(Sales sales : this.response.sales){
HashMap<String, String> hm = new HashMap<String,String>();
if (sales.getCategories1().contains("12")){
//hm.put("sale_title", "" + sales.getShort_title());
for(Shop shop : this.response.shops){
String image_file = new String( Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/images/" + shop.getImage());
if(shop.getId().equals(sales.getShop_id())){
hm.put("shop_image", image_file );
System.out.println(shop_image);
}
}
if(hm.size()>0){
gridView.setAdapter(new ImageAdapter(MainActivity.this,R.layout.grid_layout , imgArray, titleArray));
}
}
}
}
}
}
How to call images into gridview on above image? Please help.
There is easy step to crate asyntask within fragment
in your fragment place code on activityCreateview
new MyAsyncTask(getActivity(), mListView).execute("");
getActivity() is method to communicate with fragment and activity
in asynstak on post
context.mListView.setArrayAdapter(...........)
here is
public class SalesFragment extends Fragment {
GridView gridView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View gv = inflater.inflate(R.layout.hot_sales, null);
gridView = (GridView) gv.findViewById(R.id.grid_view);
bindGridView()
return gv;
//return super.onCreateView(inflater, container, savedInstanceState);
}
public void bindGridview()
{
new MyAsyncTask(getActivity(), gridView).execute("");
}
class MyAsyncTask extends AsyncTask<String, String, String>
{
GridView mGridView;
Activity mContex;
public MyAsyncTask(Activity contex,GridView gview)
{
this.mGridView=gview;
this.mContex=contex;
}
protected String doInBackground(String... params)
{
//fetch data
}
#Override
protected void onPostExecute(String result) {
{
for(Sales sales : this.response.sales){
HashMap<String, String> hm = new HashMap<String,String>();
if (sales.getCategories1().contains("12")){
//hm.put("sale_title", "" + sales.getShort_title());
for(Shop shop : this.response.shops){
String image_file = new String( Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/images/" + shop.getImage());
if(shop.getId().equals(sales.getShop_id())){
hm.put("shop_image", image_file );
System.out.println(shop_image);
}
}
}
}
if(hm.size()>0)
mcontext.mGridView.setAdapter(new ImageAdapter(mContext),hm);
}
before fetching data make it model like
public class ImageModel
{
String title;
String img;
}
ArrayList<ImageModel> arrayList=new ArrayList<ImageModel>();
fill array list with required data
then
mcontext.mGridView.setAdapter(new ImageAdapter(mContext),hm,arrayList);
//in image adapter
public class ImageAdapter extends ArrayAdapter<String> {
public ImageAdapter(Context context, HashMap<String, String> hm,ArrayList<ImageModel> images )
{
super(context, R.layout.activity_t);
}
//--code
}
use hash map in adapter and assign images with position
set data and fetch value from model

Categories

Resources