The problem is that whenever the user go to the third fragment then coming back to the first one, all the data in the first fragment will be gone.
the Data will parsed from a web service, using AsyncTask within the fragment
this my onCreate() method
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
int radius = 4;
double latitude = 51.3674718208489;
double longtitude = -0.119329656538836;
Boolean loyal = false;
int mer = 1;
try {
parameters.put(ConstantKeys.SEARCH_NAME, searchname);
parameters.put(ConstantKeys.LOYALTY, isLoyalty);
Log.d(CommunityFragment.class.getSimpleName(), parameters.toString());
} catch (JSONException e) {
e.printStackTrace();
}
FindOfferField();
}
this is my onCreateView() method
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
return rootView;
}
and this is my AsynTask()
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
rowItem = new ArrayList<RowItem>();
for (int i = 0; i < array.length(); i++) {
final JSONObject list = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(list.getInt("Id"));
items.setMerchantid(list.getInt(ConstantKeys.MERCHANTID));
items.setDescription(list.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(list.getString(ConstantKeys.DATE).replace("T00:00:00", ""));
items.setTokensFor(list.getString(ConstantKeys.FOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
listView = (ListView) getView().findViewById(R.id.listViewCommunity);
adapter = new CustomListAdapter(getActivity(), rowItem);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int ID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", ID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
UPDATE
public class CommunityFragment extends ListFragment{
//LocationListener location;
ProgressDialog progressDialog;
Context context;
public static JSONObject parameters = new JSONObject();
private static final String STATE_LIST = "State Adapter Data";
public static final String DATA = "DATA";
public CustomerAccount customerAccount;
//---------Find Parameters----------
int byID;
//CustomListAdapter adapter;
public static String TAG = CommunityFragment.class.getSimpleName();
ListView listView;
ArrayList<RowItem> rowItem;
View view;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
String searchname = ConstantSearch.SEARCHNAME;
CustomListAdapter adapter;
private String mParam1;
private String mParam2;
RowItemLoyalty getEndTask;
RowItem getTask;
RowItem storeData;
int index;
int top;
JSONArray array;
public CommunityFragment() {
}
public static CommunityFragment newInstance(String param1, String param2) {
CommunityFragment fragment = new CommunityFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String dataInJson = new Gson().toJson(rowItem);
outState.putString(DATA, dataInJson);
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null && savedInstanceState.containsKey(DATA))
{
Log.d("StringData", DATA);
String jsonData = savedInstanceState.getString(DATA);
rowItem = new Gson().fromJson(jsonData, new TypeToken<List<RowItem>>(){}.getType());
}
else
{
rowItem = new ArrayList<>();
}
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
int radius = 4;
double latitude = 51.3674718208489;
double longtitude = -0.119329656538836;
Boolean isLoyalty = false;
int mer = 1;
try {
parameters.put(ConstantKeys.SEARCH_NAME, searchname);
parameters.put(ConstantKeys.LOYALTY, isLoyalty);
Log.d(CommunityFragment.class.getSimpleName(), parameters.toString());
} catch (JSONException e) {
e.printStackTrace();
}
FindOfferField();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
rowItem = new ArrayList<RowItem>();
listView = (ListView) rootView.findViewById(R.id.listViewCommunity);
return rootView;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
rowItem = new ArrayList<RowItem>();
for (int i = 0; i < array.length(); i++) {
final JSONObject offerList = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(offerList.getInt("Id"));
items.setMerchantid(offerList.getInt(ConstantKeys.FAVORITE_MERCHANTID));
items.setDescription(offerList.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(offerList.getString(ConstantKeys.DATE_END).replace("T00:00:00", ""));
items.setTokensFor(offerList.getString(ConstantKeys.TOKENSFOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int offerID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", offerID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
public class FindOfferTask extends AsyncTask<Void, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected JSONObject doInBackground(Void... params) {
ApiSecurityManager manager = ApiSecurityManager.getInstance();
String result = manager.apiCall("Offers/find", parameters.toString(), "C");
Log.d(CommunityFragment.class.getSimpleName(), result);
JSONObject jsonResult = new JSONObject();
Log.i(getClass().getSimpleName(), result);
try
{
jsonResult = new JSONObject(result);
}
catch (JSONException e)
{
e.printStackTrace();
}
return jsonResult;
}
protected void onPostExecute(JSONObject jsonObject) {
//loadingMore = false;
progressDialog.dismiss();
}
}
}
First of all, keep your view creation outside ApiRequestListener. Initialize all views in onCreateView() only.
// Key for storing data in `savedInstance`
public static final String DATA = "DATA";
In onCreateView()
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
rowItem = new ArrayList<RowItem>();
listView = (ListView) rootView.findViewById(R.id.listViewCommunity);
return rootView;
}
When activity is created, check if data is available in savedInstanceState or not and based on that start web service.
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if(savedInstanceState.containsKey(DATA))
{
String jsonData = savedInstanceState.getString(DATA);
rowItem = new Gson().fromJson(jsonData, new TypeToken<List<RowItem>>(){}.getType());
}
else
{
rowItem = new ArrayList<>();
}
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
// Now here, check the size of array list. If it is 0, then start service to fetch data from server
}
To convert your list into string, I am using Gson library here.
#Override
public void onSaveInstanceState(Bundle outState)
{
// Here use gson library from google to convert list of data to string.
String dataInJson = new Gson().toJson(rowItem);
outState.putString(DATA, dataInJson);
super.onSaveInstanceState(outState);
}
And your method will look like this:
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
for (int i = 0; i < array.length(); i++) {
final JSONObject list = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(list.getInt("Id"));
items.setMerchantid(list.getInt(ConstantKeys.MERCHANTID));
items.setDescription(list.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(list.getString(ConstantKeys.DATE).replace("T00:00:00", ""));
items.setTokensFor(list.getString(ConstantKeys.FOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
adapter.notifyDataSetChanged();
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int ID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", ID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
Hope this helps.
Related
I am using ViewPager in my app and fetch the data(Images) from server(with JSON). Even if runs smoothly no image is shown in the viewpager.
I read so many tutorial regarding this, but nobody solve my problem. Please tell me where i am wrong...
Here is my code:
view_pager.xml
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="40dp" />
image_view.xml
<ImageView
android:id="#+id/image_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"/>
ViewPager_Adapter.java
public class ViewPager_Adapter extends PagerAdapter {
private String urls;
private LayoutInflater inflater;
private Context context;
ArrayList<String> mylist;
public ViewPager_Adapter(Context context, ArrayList<String> mylist) {
this.context = context;
this.urls = urls;
this.mylist = mylist;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return mylist.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.image_view, null);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image_adapter);
Glide.with(context)
.load(mylist.get(position))
.into(imageView);
view.addView(imageLayout,0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
View_Pager.Java
public class View_Pager extends Fragment {
private static ViewPager mPager;
JSONArray responsearray = null;
String imageOne;
private static final String TAG_PHOTO_ONE = "Gallery_Full";
ArrayList<String> myList;
HashMap<String, String> get;
ViewPager_Adapter viewpager_adapter;
LinearLayout addimages;
int REQUEST_CODE = 100;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_pager, null);
mPager = view.findViewById(R.id.viewpager);
new GetImages().execute(true);
return view;
}
class GetImages extends AsyncTask<Boolean, Void, String> {
#Override
protected String doInBackground(Boolean... booleans) {
ImageApi imageApi = new ImageApi();
String result = null;
try {
result = imageApi.galleryget(sharedPreferences.getString("id", ""));
JSONObject object = new JSONObject(result);
if (object.getString("error").equalsIgnoreCase("false")) {
responsearray = object.getJSONArray("response");
return "true";
} else {
String errormsg = object.getString(result);
return errormsg;
}
} catch (ApiException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
if (s.equalsIgnoreCase("true")) {
showList(responsearray);
}
}
}
}
public void showList(final JSONArray responsearray) {
try {
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>();
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
}
Use this code for showList() as you are not populating you're arrayList properly the data is being over write in one position .
So , what you have to do is initialize it out side of for loop .
public void showList(final JSONArray responsearray) {
try {
//here
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
Edit
Also if your final image path is as below then you have to update your code in adapter for image path as follow.
Update position in view.addView() too.
String test = String.valueOf(mylist.get(position));
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + test;
Glide.with(context)
.load(finalimgpath)
.into(imageView);
view.addView(imageLayout,position);
return imageLayout;
In your For loop you are initialising your list everytime
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>(); // THIS IS WRONG. don't initialise every time
myList.add(String.valueOf(get)); // THIS IS ALSO WRONG. you are adding hashmap object to list
}
So make your for loop like this
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(imageOne);
}
I'm new coder of android and trying to get list of images in my server and database(mysql) but I got error and I don't know what is causing it...
the error is 'E/RecyclerView: No adapter attached; skipping layout' and it happen when I'm running, anyone can help me??
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private RecyclerView recyclerView;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(RecyclerView recyclerView, Context context, boolean pattern) {
this.recyclerView = recyclerView;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
imageGalleryItems = prepareData(response);
MyAdapter adapter = new MyAdapter(context, imageGalleryItems);
recyclerView.setAdapter(adapter);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
I wrote my adapter as MyAdapter.java:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context, ArrayList<ImageGalleryItem> galleryList) {
this.galleryList = galleryList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
You can setup your recyclerView and set items when data received.
activity code for setup recycler view:
public class MainActivity extends AppCompatActivity {
private MyAdapter mAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupRecyclerView();
}
private void setupRecyclerView(){
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MyAdapter(context);
recyclerView.setAdapter(mAdapter);
}
}
Pass adapter to async task:
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private MyAdapter mAdapter;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(MyAdapter adapter, Context context, boolean pattern) {
this.mAdapter = adapter;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
imageGalleryItems = prepareData(response);
mAdapter.setItems(imageGalleryItems);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
Adapter with setItems method:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context) {
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
public void setItems(ArrayList<ImageGalleryItem> galleryList){
this.galleryList = galleryList;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
my error log
I tried to load list view in my fragment.But my app crashes on clicking the button to populate my listview. I don't know what error i did.Any help will be appreciated.I have tried most of the stuffs regarding this..But nothing works well.(i have removed some codes to avoid clumsy look)
Here is my Fragment code :
public class Func extends Fragment {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
#Override
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2, container, false);
FlowerAdapter adapter=new FlowerAdapter(getActivity().getApplicationContext(),R.layout.flower_list_xml,flowersList);
ListView listView=(ListView)rootView.findViewById(R.id.listView);
listView.setAdapter(adapter);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Button b = (Button)getView().findViewById(R.id.button);
b.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
new BackTask().execute(url);
}
});
}
// My Async task starts here
public class BackTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2", "test");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("test44", sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return result;
}
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
} catch (JSONException e) {
e.printStackTrace();
}
You return null in your doInBackground, which you then attempt to parse as a JSONArray in your OnPostExecute. Return a proper String from your doInBackground method, and see if that helps.
Do a null check before using getView() like
if(getView()!=null){
//Your code
}
Also it is better to initialize the button in oncreate view using the rootview intead of getview()
EDIT:
Your network call which your are doing has to be moved to doInBackground as it should be done in background thread and fetch the result.The fetched result should be added to the list in onPostExecute.Hope this helps you
public class SampleClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
BufferedReader reader = null;
String result=null;
try {
URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2", "test");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("test44", sb.toString());
result= sb.toString();
} catch (Exception e) {
e.printStackTrace();
result= null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
result= null;
}
}
return result;
}
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
you can try with view insteadof getView() in onViewCreated() method.
public class ListView extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button b = (Button) view.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new BackTask().execute("http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData");
}
});
}
private class BackTask extends AsyncTask<String, Void, String> {
String result;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
result = Utility.executeHttpGet(params[0]);
} catch (Exception e) {
Log.e("ListView", e.getMessage(), e);
}
return result;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ar = new JSONArray(s);
for (int i = 0; i < ar.length(); i++) {
JSONObject jsonObject = ar.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try this code
public class Listview extends Fragment {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
ListView listview;
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView!= null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
rootView = inflater.inflate(R.layout.tab2, container, false);
} catch (InflateException ignored) {
}
listView=(ListView)rootView.findViewById(R.id.listView);
Button b = (Button)rootView.findViewById(R.id.button);
b.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
new BackTask().execute(url);
}
});
return view;
}
private class BackTask extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
return null;
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
FlowerAdapter adapter=new FlowerAdapter(getActivity(),R.layout.flower_list_xml,flowersList);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
i am trying to send Data (ID value) from one activity to other
but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code
public class Order extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
new JSONTask().execute("http://146.185.178.83/resttest/order");
}
public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<OrderModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<OrderModel> orderModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
orderModelList.add(orderModel);
}
return orderModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<OrderModel> result) {
super.onPostExecute(result);
dialog.dismiss();
OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);
lvUsers.setAdapter(adapter);
}
}
public class OrderAdapter extends ArrayAdapter {
public List<OrderModel> orderModelList;
private int resource;
private LayoutInflater inflater;
public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
super(context, resource, objects);
orderModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
final int orderId = orderModelList.get(position).getId();
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderId);
startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
private Button bOrderNo;
}
}
}
The holder gets executed in loop i guess is why it wouldn't send right Id.
How do i get it to send only Id of the clicked orderId
you can check this link to see how json Response looks like http://146.185.178.83/resttest/order
You have a silly mistake in your code . I have edited single line in your code . I think you are getting same "orderId" every time instead of actual "orderId". Check this one . I hope your problem will resolve .
final int index = position;
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderModelList.get(index).getId());
startActivity(intent);
}
});
Please try
In place of
intent.putExtra("parameter_name", orderId);
Please put
intent.putExtra("parameter_name", orderModelList.get(position).getId());
So I'm trying to make a simple application that makes stores group events in a MySQL database then retrieves them for people to join. In this fragment I list all the events by using a JSONParser class to query the database. I use an Async class to do the querying. The fragment will initially query the db on startup or whenever the user decides to limit the scope of the events by selecting something in a spinner or when the user pushes a refresh button. I have been getting messages like
Choreographer﹕ Skipped 95 frames! The application may be doing too much work on its main thread.
while running the program and I'm not sure why. I think it might be because I call the Async class too much, but I'm not sure.
public class mainActivityFragment extends Fragment {
final public String information = "information";
public Spinner specifySubject;
private ArrayList<String> list = new ArrayList<>();
private ArrayList<EventObject> eventList = new ArrayList<>();
JSONParser jsonParser = new JSONParser();
ListView test;
ArrayAdapter adapter;
// url to create new product
private static String url_get_event = "";
private ProgressDialog pDialog;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, list);
test = (ListView) v.findViewById(R.id.listView);
new CreateNewProduct().execute();
if(pDialog.isShowing()){
pDialog.dismiss();
}
test.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent in = new Intent(getActivity(), AttendInformation.class);
EventObject clickedEvent = eventList.get(position);
String[] testInformation = {clickedEvent.getTo().toString(), clickedEvent.getLocation(), clickedEvent.getTitle(), clickedEvent.getDurationString(), clickedEvent.getDescription(), clickedEvent.getSubject()};
in.putExtra(information, testInformation);
startActivity(in);
}
});
Button createEventButton = (Button) v.findViewById(R.id.Button2);
createEventButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent in = new Intent(getActivity(), createEvent.class);
startActivity(in);
}
});
specifySubject = (Spinner) v.findViewById(R.id.spinner);
specifySubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (position == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[position];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Button refresh = (Button) v.findViewById(R.id.leftButton);
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (specifySubject.getSelectedItemPosition() == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[specifySubject.getSelectedItemPosition()];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
});
return v;
}
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Events...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
JSONArray jsonArr = jsonParser.getJSONFromUrl(url_get_event);
for(int n = 0; n < jsonArr.length(); n++)
{
try {
JSONObject object = jsonArr.getJSONObject(n);
if(!list.contains(object.getString("title"))){
String[] time = object.getString("time").split(":");
time[1] = time[1].substring(0, 2);
EventObject tempEven = new EventObject(object.getString("title"), object.getString("location"), object.getString("description"), object.getString("subject"), 0, new TimeObject(Integer.parseInt(time[0]), Integer.parseInt(time[1])));
eventList.add(tempEven);
list.add(object.getString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
test.setAdapter(adapter);
pDialog.dismiss();
}
}
}