I have a View Pager in my App. The View pager gets the Imagepath from the JSON & shows in a ImageView. The View pager works for the first time. But when the values are changed, it returns a error.
But I have notified the PagerAdapter about the notifyDataSetChanged.
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 1, found: 0 Pager id: com.hello.hello:id/pager Pager class: class com.hello.hello.utils.ImageViewTouchViewPager Problematic adapter: class com.hello.hello.utils.ZoomAdapter
ASYNCTASK 1
public class FetchPromo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
promoList = new ArrayList<String>();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Promotions from your Neighbouring store");
progress.show();
progress.setCanceledOnTouchOutside(false);
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://46.101.126.31/mobileapp/gps/api.php?rquest=get_promotions&latitude=" + userLocation.getLatitude() + "&longitude=" + userLocation.getLongitude();
Log.d("Path", url);
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
try {
JSONObject jsonObject = new JSONObject(jsonData);
store_name = jsonObject.getString("store_name");
JSONArray promo_path = jsonObject.getJSONArray("image_path");
Log.d("Path", store_name);
for (int i = 0; i < promo_path.length(); i++) {
String path = promo_path.getString(i);
promoList.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
store.setText(store_name);
if (promoList.isEmpty()) {
promoList.add(placeholder);
}
mZoomAdapter = new ZoomAdapter(getActivity(), promoList);
mViewPager.setAdapter(mZoomAdapter);
mZoomAdapter.notifyDataSetChanged();
new FetchStore().execute();
progress.dismiss();
}
}
AYNCTASK 2 (where the data has to be loaded again)
public class FetchPromoByID extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
promoList.clear();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Promotions from your Choosen store");
progress.show();
progress.setCanceledOnTouchOutside(false);
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://46.121.116.31/mobileapp/gps/api.php?rquest=get_promotions_by_store_id&store_id=" + Choosen_id;
Log.d("FetchPromoByID", url);
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray promo_path = jsonObject.getJSONArray("image_path");
store_name = jsonObject.getString("store_name");
Log.d("Path", store_name);
for (int i = 0; i < promo_path.length(); i++) {
String path = promo_path.getString(i);
promoList.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mZoomAdapter = new ZoomAdapter(getActivity(), promoList);
mViewPager.setAdapter(mZoomAdapter);
mZoomAdapter.notifyDataSetChanged();
new FetchStore().execute();
progress.dismiss();
}
}
ADAPTER
public class ZoomAdapter extends PagerAdapter {
private Context context;
private ArrayList<String> IMAGES = new ArrayList<>();
public ZoomAdapter(Context context, ArrayList<String> IMAGES) {
this.IMAGES = IMAGES;
this.context = context;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public View instantiateItem(ViewGroup container, int position) {
String url = IMAGES.get(position);
PhotoView photoView = new PhotoView(container.getContext());
// Now just add PhotoView to ViewPager and return it
container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
Picasso.with(context)
.load(url)
.fit()
.into(photoView);
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
FetchStore
public class FetchStore extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
storeList = new ArrayList<String>();
storeID = new ArrayList<String>();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://46.101.116.31/mobileapp/gps/api.php?rquest=get_store";
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray storearray = jsonObject.getJSONArray("stores");
for (int i = 0; i < storearray.length(); i++) {
JSONObject storeobj = storearray.getJSONObject(i);
String store = storeobj.getString("name");
String ID = storeobj.getString("id");
storeList.add(store);
storeID.add(ID);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
choose.setVisibility(View.VISIBLE);
}
}
I have found many similar Questions like this. But none of the solution worked for me. Please guide me.
Thanks in Advance
I think your error is here (Async Task #2)
#Override
protected void onPreExecute() {
super.onPreExecute();
promoList.clear();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Promotions from your Choosen store");
progress.show();
progress.setCanceledOnTouchOutside(false);
}
You make promoList.clear() (set the count to 0),which used in ZoomAdapter instance without notifying.
So notify adapter there or make a temporary ArrayList and clear / addAll in onPostExecute
Related
I hope someone out there can help me solve my problem. I have android app that have 3 tabs, i use fragment, first tab is recyclerView list, second tabs is map. the problem is in tabs 1, i need to fetch data with volley to recyclerView on tabs 1, if run fine but i cannot see the data on first app start, but when i change tab and back to tab 1 again it will refresh the data and show the data on recyclerView.
Adapter.java
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Warkop> mWarkop;
private LayoutInflater inflater;
public CustomListAdapterWarkop(Context context, List<Warkop> mWarkop) {
this.context=context;
inflater= LayoutInflater.from(context);
this.mWarkop = mWarkop;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_warkop_row, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder viewHolder = (ItemViewHolder) holder;
Warkop current = mWarkop.get(position);
viewHolder.tvNamaWarkop.setText(current.getNamaWarkop());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.noimage)
.showImageOnFail(R.drawable.noimage)
.showImageOnLoading(R.drawable.noimage).build();
imageLoader.displayImage(current.getFotoWarkop(), viewHolder.ivFotoWarkop, options);
}
#Override
public int getItemCount() {
return mWarkop.size();
}
}
ItemHolder.java
package com.andylah.warkopedia;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by andylah on 11/3/2017.
*/
public class ItemViewHolder extends RecyclerView.ViewHolder {
public ImageView ivFotoWarkop;
public TextView tvNamaWarkop;
public ItemViewHolder(View itemView) {
super(itemView);
tvNamaWarkop = itemView.findViewById(R.id.nama_warkop);
ivFotoWarkop = itemView.findViewById(R.id.image_warkop);
}
}
Tab 1.java
public class tabSatu extends Fragment {
private static final String TAG = tabDua.class.getSimpleName();
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private boolean isFragmentLoaded = false;
View vTabSatu;
private RecyclerView recyclerView;
public static List<Warkop> warkopList = new ArrayList<Warkop>();
private CustomListAdapterWarkop warkopAdapter;
public tabSatu(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new AsyncFetch().execute();
vTabSatu = inflater.inflate(R.layout.tabsatu_view, container, false);
recyclerView = vTabSatu.findViewById(R.id.warkop_container);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
Log.d("LOG : ", "onCreatedView Run");
// Inflate the layout for this fragment
return vTabSatu;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
Log.d("LOG : ", "onViewCreated Run");
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isFragmentLoaded ) {
// Load your data here or do network operations here
isFragmentLoaded = true;
//new AsyncFetch().execute();
}else{
isFragmentLoaded = false;
Log.d("LOG : ", "isFragmentLoaded = false");
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pDialog = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading list warkop ...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... strings) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL(AppConfig.LOAD_WARKOP);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try{
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if(!error){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
warkop.setNamaWarkop(jsonObject.getString("nama_warkop"));
warkop.setAlamatWrkop(jsonObject.getString("alamat_warkop"));
warkop.setKotaWarkop(jsonObject.getString("kota_warkop"));
warkop.setLatWarkop(Double.parseDouble(jsonObject.getString("lat_warkop")));
warkop.setLangWarkop(Double.parseDouble(jsonObject.getString("long_warkop")));
warkop.setIsWifi(Integer.parseInt(jsonObject.getString("is_wifi")));
warkop.setIsToilet(Integer.parseInt(jsonObject.getString("is_toilet")));
warkop.setIsTv(Integer.parseInt(jsonObject.getString("is_tv")));
warkop.setIsColokan(Integer.parseInt(jsonObject.getString("is_colokan")));
warkop.setIsParkir(Integer.parseInt(jsonObject.getString("is_parkir")));
warkop.setFotoWarkop(jsonObject.getString("foto_warkop"));
warkopList.add(warkop);
}
}else{
String errorMsg = object.getString("error_msg");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
Problem: Even you call notifyDataSetChanged() but there are no data in Adapter.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
}
So you need to set and notify warkopList to Adapter after API call. It will help you.
tabSatu:
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try {
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if (!error) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
...
warkopList.add(warkop);
adapter.setItems(warkopList);
}
}
...
}
CustomListAdapterWarkop: add setItem() method to Adapter
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
...
public void setItems(List<WarkopList> warkopList) {
mWarkop = warkopList;
notifyDataSetChanged();
}
...
}
I am trying to get data from server using AsyncTask, on first time result not showing, but its working from second time. I seen so many examples but none of them working for me. please see my code below
private void event_load_data_from_server(int id){
AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/posteventlist.php?city="+ucl+"&eveid="+eveid+"&id="+integers[0])
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
if(object.has("name")){
pname=object.getString("name");
}else{
pname="";
}
if(object.has("timestamp")){
timestamp =object.getString("timestamp");
}else{
timestamp="";
}
if(object.has("id")){
eveid=object.getInt("id");
}else {
eveid=0;
}
if(object.has("address")){
address=object.getString("address");
}else {
address="";
}
if(object.has("thumbnail")){
thumbnail=object.getString("thumbnail");
}else {
thumbnail="";
}
EventPost events = new EventPost(pname, eveid, thumbnail,address,timestamp);
eventPostList.add(events);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Events Loading Wait...");
showDialog();
}
#Override
protected void onPostExecute(Void aVoid) {
hideDialog();
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
Whenever you want to use onPostExecute() method in AsyncTask, just make sure use String or other type instead of Void as result parameter of AsyncTask<x, y, String> where x,y are any data type(Integer,String,etc..).
Therefore, make changes in code as per below:
Make both AsyncTask<...> like this AsyncTask<Integer,Void,String>
Change return type of doInBackground from Void to String
Change return null; with return ""; at last line in doInBackground.
Change onPostExecute(Void aVoid) to onPostExecute(String s) for override function of onpostexecute.
Then try it.
private void event_load_data_from_server(int id){
AsyncTask<Integer,Void,JSONArray> task = new AsyncTask<Integer, Void, JSONArray>() {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/posteventlist.php?city="+ucl+"&eveid="+eveid+"&id="+integers[0])
.build();
#Override
protected JSONArray doInBackground(Object... integers) {
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
return array;
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Events Loading Wait...");
showDialog();
}
#Override
protected void onPostExecute(JSONArray array) {
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
if(object.has("name")){
pname=object.getString("name");
}else{
pname="";
}
if(object.has("timestamp")){
timestamp =object.getString("timestamp");
}else{
timestamp="";
}
if(object.has("id")){
eveid=object.getInt("id");
}else {
eveid=0;
}
if(object.has("address")){
address=object.getString("address");
}else {
address="";
}
if(object.has("thumbnail")){
thumbnail=object.getString("thumbnail");
}else {
thumbnail="";
}
EventPost events = new EventPost(pname, eveid, thumbnail,address,timestamp);
eventPostList.add(events);
}
hideDialog();
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
I am trying to fetch data from MySQL database and display it in listview. The data is successfully retrieved but the listview is not populated until the screen display is off. Progress dialog also doesn't appear until the listview is populated. Any suggestions?
public class BestLinksActivity extends AppCompatActivity {
public ListView myListView;
public MyListViewAdapter mAdapter;
public List<HotelInfo> dataSource;
private String cityName;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_best_links);
dataSource = new ArrayList<>();
mProgressDialog = new ProgressDialog(BestLinksActivity.this);
mProgressDialog.setMessage("Loading data...");
Bundle extras = getIntent().getExtras();
if (extras != null) {
cityName = extras.getString("City");
}
DataBaseReader dbReader = new DataBaseReader();
if (!(cityName.equals(null))) {
dbReader.execute(cityName);
} else {
Toast.makeText(getApplicationContext(), "City name not specified", Toast.LENGTH_SHORT).show();
}
//Create adapter
mAdapter = new MyListViewAdapter(getApplicationContext(), dataSource);
//Configure the listview
myListView = (ListView) findViewById(R.id.main_list_view);
myListView.setAdapter(mAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item value
HotelInfo currentItem = dataSource.get(position);
//Open url of the currentItem in web browser
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(currentItem.getLinkUrl())));
}
});
}
public String getTitle(String url) {
String[] subStrings = url.split("/");
String urlTitle = "";
for (int i = 0; i < subStrings.length; i++) {
if (subStrings[i].equals("t"))
urlTitle = (subStrings[i + 1]);
}
urlTitle = urlTitle.replace("-", " ");
urlTitle=((urlTitle.charAt(0)+"").toUpperCase()).concat(urlTitle.substring(1));
return urlTitle;
}
public class DataBaseReader extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.build();
Log.d("CheckParam", params[0]);
RequestBody postBody = new FormBody.Builder()
.add("cityName", params[0])
.build();
Request myRequest = new Request.Builder()
.url("http://172.18.0.32/extractData.php")
.post(postBody)
.build();
String serverResponse = null;
try {
Response response = okHttpClient.newCall(myRequest).execute();
serverResponse = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject myJsonObj = new JSONObject(serverResponse);
JSONArray myJsonArray = myJsonObj.getJSONArray("server_response");
for (int index = 0; index < myJsonArray.length(); index++) {
JSONObject linkObject = myJsonArray.getJSONObject(index); //Otherwise, you will get last element
HotelInfo myHotelInfo = new HotelInfo();
myHotelInfo.setLinkUrl(linkObject.getString("Link"));
myHotelInfo.setLinkTitle(getTitle(myHotelInfo.getLinkUrl()));
dataSource.add(myHotelInfo);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Log.d("MyKeyser", serverResponse);
return serverResponse;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("MyKey", s);
if (mProgressDialog!=null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
}
Add the following line to your onPostExecute:
mAdapter.notifyDataSetChanged();
You need to notify your adapter that the data had changed.
See the docs.
Regarding the ProgressBar, you need to put it under some Layout in your activity_best_links layout.
The best way would be to not create it programatically, but add it to your xml layout file, see example here, and then play with its visibility via mProgress.setVisibility();
I want show 3 fragments in my Activity and load data from json in any fragments! I want show each json data into one fragment, but in my application copy duplicate json data in fragment one !
For example : when running application show 1 post in any fragment but when swipe between tabs copy json data below posts!
myEvent (custom eventBus code) :
public class MyEvent {
public String fragmentTag ;
private List<DataModel> infoModels = new ArrayList();
public MyEvent (String tag,List<DataModel> models){
this.fragmentTag = tag;
this.infoModels = models;
}
public List<DataModel> getInfoModels() {
return infoModels;
}
}
Fragment 1 codes:
public class free_fragment extends Fragment {
private RecyclerView mRecyclerView;
private free_recycler_adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<DataModel> dataModels = new ArrayList<DataModel>();
private Context context;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_free_layout, container, false);
context = getContext();
LoadData();
///----- RecyclerView -----
mRecyclerView = (RecyclerView) view.findViewById(R.id.pdf_RecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new free_recycler_adapter(context, dataModels);
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Subscribe
public void onEvent(MyEvent event) {
List<DataModel> dataModels = event.getInfoModels();
if (event.fragmentTag.equals("forfragment1")) {
mAdapter.add(dataModels);
mAdapter.notifyDataSetChanged();
}
}
private void LoadData() {
freeDataInfo dataInfo = new freeDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getFreeDataInfo(context);
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}
Fragment 1 AsyncTask codes:
public class freeDataInfo {
private Context mContext;
private String ServerAddress = freeServer_IP.getFreeIP();
public void getFreeDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "limit=10");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<DataModel> infoModels = new ArrayList<>();
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress + "limit=10")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("result");
for (int i = 0; i <= postsArray.length(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("publishDate");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("error2", String.valueOf(e));
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
//CustomProcessDialog.dissmis();
//Stop Progress
if (dialog.isShowing()) {
dialog.dismiss();
}
if (result != null) {
bus.post(new MyEvent("forfragment1", infoModels));
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}
Other fragments codes such as fragment one code!
How to fix this problem and not copy (duplicate) json datas below posts??! Thanks all <3
First You Clear ArrayList Than Add Data In ArrayList in Every Call of AsyncTask
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
infoModels.clear();
}
i 'm working asynctask.i have two asynctas one activity.In first asynctask i use to parse json and show it in listview and second- to download images by position.
this is a my code
public class MainmoviesList extends Fragment implements
AdapterView.OnItemSelectedListener {
public final static String TAG = MainmoviesList.class.getSimpleName();
String imageurl = "**********";
public static List<ServerItems> arrayOfList;
private ProgressDialog pDialog2;
public static Gallery main_listview;
private AzercellMainPageAdapter objAdapter;
private RelativeLayout mSwitcher;
private CustomerStatistic cs;
private String Eng_Url = "*************"; // eng
public static int mPosition;
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);
main_listview.setOnItemSelectedListener(this);
main_listview.setSelection(mPosition);
arrayOfList = new ArrayList<ServerItems>();
cs = new CustomerStatistic();
cs.execute(Eng_Url);
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 {
Globalclass.MovieServer = result;
JSONArray mainJson = new JSONArray(result);
for (int i = 0; i < mainJson.length(); i++) {
JSONObject objJson = mainJson.getJSONObject(i);
JSONObject cinema = objJson.getJSONObject("Cinemas");
JSONArray mainJson1 = cinema.getJSONArray("Cinemaname");
for (int j = 0; j < mainJson1.length(); j++) {
JSONObject objJson1 = mainJson1.getJSONObject(j);
Log.e("cinema name", objJson1.getString("cinemaName"));
}
ServerItems 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.setStars(objJson.getString("stars"));
objItem.setBlurimage(imageurl
+ objJson.getString("ipone_4_blur"));
arrayOfList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
setAdapterToListview();
}
}
public void setAdapterToListview() {
// objAdapter = new AzercellMainPageAdapter(getApplicationContext(),
// R.layout.azercell_main_page_adapter, arrayOfList);
objAdapter = new AzercellMainPageAdapter(getActivity(),
R.layout.azercell_main_page_adapter, arrayOfList);
main_listview.setAdapter(objAdapter);
}
public void loadimagePosition(int pos) {
}
private void SendFlagIdToServer1(final int position) {
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog2 = new ProgressDialog(getActivity());
pDialog2.setCancelable(false);
pDialog2.show();
pDialog2.setContentView(R.layout.custom_progressdialog);
}
#Override
protected String doInBackground(String... params) {
URL url;
try {
url = new URL(arrayOfList.get(position).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();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog2 != null) {
pDialog2.dismiss();
pDialog2 = null;
}
}
}
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
httpGetAsyncTask.execute();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
mPosition = position;
SendFlagIdToServer1(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
i have runtime exception.both asynctas classes runing same time?
it is a possible to run same asynctass in same time one activity?
if anyone knows solution please help me
thanks