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();
}
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 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 show websites data into Recyclerview with OkHTTP v3 library.
I want show this datas for offline, my mean is if user turn off data/wifi show this datas for offline. but i do not want use SQLite Database!
Can i use OkHTTP cache? i don't know how to use okhttp cache.
AsyncTask code:
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");
new getInfo().execute(ServerAddress);
}
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);
//infoModels = new ArrayList<>();
// Initiate Progress
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
infoModels.clear();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
//.url(ServerAddress + "limit=10")
.url(ServerAddress)
.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("full_description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("date");
String url = postObject.getString("url");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "Post url: " + url);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, url, 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, "اتصال اینترنت خود را بررسی کنید", Toast.LENGTH_LONG).show();
}
}
}
}
Adapter codes:
public class free_recycler_adapter extends RecyclerView.Adapter<free_recycler_adapter.ViewHolder> {
private List<DataModel> mDateSet;
private Context context;
// Provide a suitable constructor (depends on the kind of dataset)
public free_recycler_adapter(Context context, List<DataModel> dataSet) {
this.context = context;
this.mDateSet = dataSet;
}
// Create new views (invoked by the layout manager)
#Override
public free_recycler_adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.free_card_layout, parent, false);
// create ViewHolder
return new ViewHolder(view);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
viewHolder.free_titleText.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
Glide.with(context)
.load(mDateSet.get(position).getImage())
.placeholder(R.drawable.ic_download_image)
.crossFade()
.into(viewHolder.free_avatarImage);
viewHolder.free_descText.setText(Html.fromHtml(mDateSet.get(position).getDescription()));
viewHolder.free_descText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
.putExtra("title", mDateSet.get(position).getTitle())
.putExtra("desc", mDateSet.get(position).getDescription())
.putExtra("image", mDateSet.get(position).getImage())
.putExtra("url", mDateSet.get(position).getUrl())
.putExtra("category", mDateSet.get(position).getCategory())
.putExtra("date", mDateSet.get(position).getDate()));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<DataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<DataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView free_titleText, free_descText;
public ImageView free_avatarImage;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
free_titleText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_title);
free_descText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_content);
free_avatarImage = (ImageView) itemLayoutView.findViewById(R.id.pdf_card_image);
}
}
}
Fragment 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;
private boolean isDataFetched;
private boolean mIsVisibleToUser;
private View view;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_free_layout, container, false);
context = getContext();
if (mIsVisibleToUser) {
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 (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
//mAdapter.setLoaded();
}*/
if (event.fragmentTag.equals("forfragment1")) {
mAdapter.add(dataModels);
isDataFetched = true;
mAdapter.notifyDataSetChanged();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
mIsVisibleToUser = isVisibleToUser;
if (isVisibleToUser && !isDataFetched && getContext() != null) {
context = getContext();
LoadData(); //Remove this call from onCreateView
}
}
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();
}
}
How can i show data for offline without Sqlite DataBase? Thanks all <3
if (isNetworkStatusAvialable(ctx)) {
//Here your normal parsing while network available
SharedPreferences app_preferences1 = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = app_preferences1.edit();
editor.putString("jsonresponse", "yourjsonresponse");
editor.commit();
} else {
final SharedPreferences app_preferences1 = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String response= app_preferences1.getString("jsonresponse", "");
try {
JSONObject postObj = new JSONObject(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("full_description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("date");
String url = postObject.getString("url");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "Post url: " + url);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, url, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
if (netInfos.isAvailable())
return true;
}
return false;
}
Here is a good example for how to use JsonWriter
And here is the documentation for JsonWriter.
This should do it for writing into a json file.
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));
JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
obj.put("messages", list);
try {
FileWriter file = new FileWriter("c:\\test.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}
And when you want to read this again use this code:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\test.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts.
I can show title, description and thumbnail. but i want show medium from thumbnail_images instance of thumbnail. I don't know how to read images from medium ?!
My Json Link : Link
AsyncTaskCodes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.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.getJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.optJSONObject("medium");
String mediumImage = mediumObj.getString("url");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString(mediumImage)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
for fetch medium image i use this code :
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.optJSONObject("medium");
String mediumImage = mediumObj.getString("url");
but when set mediumImage for infoModels.add(new MainDataModel() not show me any posts!
How can set images from medium ? thanks all <3
private void setImageWithPicaso(String imageUrl) {
if (!(imageUrl == null)) {
Picasso.with(getActivity()).load(imageUrl).placeholder(R.drawable.placeholder_background).into(imageView, new Callback() {
#Override
public void onSuccess() {
//On Success
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
//On Error
}
});
} else {
spinner.setVisibility(View.GONE);
//On Error
}
}
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