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();
}
}
}
Related
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();
}
}
}
}
}
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.
I'm encountering a problem, when I try running an asynchronous task on refresh using a swipe refresh layout it "freezes" and doesn't rotate. When the task is done it just disappears.
Here is my code:
HotActivityFragment.java:
public class HotActivityFragment extends Fragment {
ListView hotList;
SwipeRefreshLayout mSwipeRefreshLayout;
Context context;
SharedPreferences sharedPreferences;
HotListAdapter hotListAdapter;
public HotActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hot, container, false);
context = getContext();
mSwipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.activity_main_swipe_refresh_layout);
hotList = (ListView)view.findViewById(R.id.hotListView);
hotList.setOnScrollListener(new EndlessScrollListener(getActivity()));
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
try {
ArrayList<ListTypeItem> initial_list = new DownloadPosts(getActivity()).execute().get();
this.hotListAdapter = new HotListAdapter(getContext(), initial_list);
hotList.setAdapter(hotListAdapter);
}catch(Exception e)
{
Log.d("Download Error", e.toString());
}
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrievePosts();
}
});
mSwipeRefreshLayout.setColorSchemeResources(R.color.accentColor, R.color.backgroundColor);
return view;
}
public void retrievePosts()
{
// showing refresh animation before making http call
mSwipeRefreshLayout.setRefreshing(true);
//shared preferences = empty
sharedPreferences.edit().putString("last_time_downloaded", "empty").commit();
try {
ArrayList<ListTypeItem> listItems = new DownloadPosts(getActivity(), mSwipeRefreshLayout).execute().get();
hotListAdapter.updateList(listItems);
hotListAdapter.notifyDataSetChanged();
} catch (Exception e) {
Log.d("Download Error", e.toString());
}
mSwipeRefreshLayout.setRefreshing(false);
//for testing purposes
// new Handler().postDelayed(new Runnable() {
// #Override public void run() {
// mSwipeRefreshLayout.setRefreshing(false);
// }
// }, 5000);
}
}
DownloadPosts.java:
public class DownloadPosts extends AsyncTask<Void, Void, ArrayList<ListTypeItem>> {
SharedPreferences sharedPreferences;
SwipeRefreshLayout swipeRefreshLayout;
public DownloadPosts(Activity activity)
{
this.sharedPreferences = activity.getPreferences(Context.MODE_PRIVATE);
}
public DownloadPosts(Activity activity, SwipeRefreshLayout swipeRefreshLayout)
{
this.sharedPreferences = activity.getPreferences(Context.MODE_PRIVATE);
this.swipeRefreshLayout = swipeRefreshLayout;
}
#Override
protected ArrayList<ListTypeItem> doInBackground(Void... args)
{
StringBuilder parsedString = new StringBuilder();
ArrayList<ListTypeItem> downloadList = new ArrayList<>();
StringBuilder str = new StringBuilder();
if(sharedPreferences.getBoolean("Thomas More",false))
{
str.append("190155257998823,");
}
String school_url = str.toString();
if(school_url.length() > 0)
{
school_url = school_url.substring(0, str.length()-1);
}
try{
String date = "";
//checken of opnieuw moet bepaald worden
// + in de adapter moet als gereload wordt last_time_downloaded == empty
if(!sharedPreferences.getString("last_time_downloaded","empty").equals("empty"))
{
String last_date = sharedPreferences.getString("last_time_downloaded","nothing");
last_date = last_date.replace(" ","T");
date= "&datum_last_posted=" + last_date;
}
URL url = new URL("http://localhost/getpostlist.php?school_post=" + school_url + date);
URLConnection conn = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null)
{
parsedString.append(json + "/n");
}
String s = parsedString.toString().trim();
//converten van string opgehaald via http naar jsonobject
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++)
{
JSONObject tempObj = array.getJSONObject(i);
School_WithoutImage tempSchool = new School_WithoutImage(tempObj.getString("school_id"),
tempObj.getString("post_message"),tempObj.getInt("views"),tempObj.getInt("likes")
,tempObj.getInt("post_id"),tempObj.getString("datum_posted"));
downloadList.add(tempSchool);
if(i == array.length()-1) {
sharedPreferences.edit().putString("last_time_downloaded",tempObj.getString("datum_posted")).commit();
}
}
JSONObject obj = array.getJSONObject(0);
}catch(Exception e)
{
Log.d("Exception", e.toString());
}
return downloadList;
}
#Override
protected void onPostExecute(ArrayList<ListTypeItem> result)
{
if(this.swipeRefreshLayout != null)
{
// swipeRefreshLayout.setRefreshing(false);
}
}
}
I have no idea why the swiperefreshview doesn't spin. Anyone has an idea?
Because the call to get():
.execute().get()
Forces the UI thread to wait for the AsyncTask to finish.
Instead you should look at doing this in the onPostExecute method:
protected void onPostExecute(ArrayList<ListTypeItem> listItems) {
hotListAdapter.updateList(listItems);
hotListAdapter.notifyDataSetChanged();
}
Because you are waiting for the result from asynctask by calling get just after execute. And further passing it to list.
You can use Local Broadcast Listener or can create an interface and can us that as callback, without freezing UI
This happens while loading data in gridview. This is my fragment containing scroll listener over gridview. But whenever i reload the data then whole gridview reload and scroll starts from top not from where the data is loaded. I am using single gridview.
public class Women_Ethnic_Fragment extends Fragment {
private static String url = "http://------/-------";
private int mVisibleThreshold = 5;
private int mCurrentPage = 0;
private int mPreviousTotal = 0;
private boolean mLoading = true;
private boolean mLastPage = false;
public Women_Ethnic_Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.gridview_fragment, container,
false);
setRetainInstance(true);
arrayList = new ArrayList<Items>();
gridView = (GridView) rootView.findViewById(R.id.gridView1);
new LoadData().execute(url);
//scrolling portion
gridView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view,
int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
if (mCurrentPage + 1 > 50) {
mLastPage = true;
}
}
}
if (!mLastPage
&& !mLoading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
//new asynctask called
new LoadData()
.execute("http://-------/---------");
mLoading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
});
return rootView;
}
//my asynctask
private class LoadData extends AsyncTask<String,
Void, Void> {
#Override
protected void onPostExecute(Void result) {
tp.dismiss();
adap = new Grid_View_Adatper(getActivity().getApplicationContext(),
arrayList);
gridView.setAdapter(adap);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
tp = new TransparentProgressDialog(getActivity(),
R.drawable.spinner);
tp.setCancelable(false);
tp.setCanceledOnTouchOutside(false);
tp.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urls[0]);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
String price = e.getString("price");
String image = e.getString("image");
String code = e.getString("sku");
tems = new Items(name, price, image, code);
arrayList.add(tems);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (RuntimeException e) {
}
return null;
}
}
Please help someone.
Thanks in advane.
The problem is you instantiate adapter over and over again. Instead check your adapter first, if it is not null, then set your data, then notify dataset changes.
if (adapter == null) {
adapter = new GridViewAdapter...
gridView.setAdapter(adapter)
}
// list refers the list inside in your adapter
list.addAll(newList); // or do your implementation
adapter.notifyDataSetChanged();
Posts.java
public class Posts extends Activity implements OnCheckedChangeListener {
private static final String TAG = "POSTS";
private static final int NULL_COUNTRY_CODE = 6;
private static final int POST_BACK_BTN = 7;
private static final int CHANGE = 8;
private String un;
private SimpleAdapter simpleAdpt;
private EditText post;
private RadioGroup radGrp;
private GPSTracker mGPS;
private PullToRefreshListView lv;
private String initial = "Se eida ";
private String code;
private String unm;
private String postui;
private String tmp;
private String idPost;
// The data to show
private List<Map<String, String>> postsList = new ArrayList<Map<String, String>>();
JSONArray array = null;
private static List<String> list = new ArrayList<String>();
private String pst;
private AlertDialogFragments adf;
private FragmentTransaction ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
initLocation();
if (code == null) {
ft = getFragmentManager().beginTransaction();
// Create and show the dialog.
adf = new AlertDialogFragments(NULL_COUNTRY_CODE);
adf.show(ft, "dialog");
}
init();
}
private HashMap<String, String> createPost(String key, String name) {
HashMap<String, String> post = new HashMap<String, String>();
post.put(key, name);
return post;
}
private void initLocation() {
mGPS = new GPSTracker(this);
final double mLat = mGPS.getLatitude();
final double mLong = mGPS.getLongitude();
getAddress(mLat, mLong);
}
private void getAddress(double mLat, double mLong) {
try {
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(mLat, mLong, 100);
if (addresses.size() > 0) {
addresses = gcd.getFromLocation(mLat, mLong, 1);
code = addresses.get(0).getCountryCode();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void init() {
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Intent i = getIntent();
un = i.getStringExtra("un");
post = (EditText) findViewById(R.id.lbl_txt);
radGrp = (RadioGroup) findViewById(R.id.rdg);
radGrp.setOnCheckedChangeListener(this);
// We get the ListView component from the layout
lv = (PullToRefreshListView) findViewById(R.id.listView);
// Set a listener to be invoked when the list should be refreshed.
((PullToRefreshListView) lv)
.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
((PullToRefreshListView) lv)
.setLastUpdated(new SimpleDateFormat(
"dd-MM-yyyy HH:mm").format(new Date()));
new GetData().execute();
}
});
simpleAdpt = new CustomAdapter(this, postsList,
android.R.layout.simple_list_item_1, new String[] { "post" },
new int[] { android.R.id.text1 });
new GetData().execute();
}
public class CustomAdapter extends SimpleAdapter {
HashMap<String, String> map = new HashMap<String, String>();
public CustomAdapter(Context context,
List<? extends Map<String, String>> data, int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
if (row != null) {
if (position % 2 == 0)
row.setBackgroundResource(R.drawable.listview_selector_even);
else
row.setBackgroundResource(R.drawable.listview_selector_odd);
}
return row;
}
}
private class GetData extends AsyncTask<String, String, String> {
private ProgressDialog progDailog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog = new ProgressDialog(Posts.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
}
#Override
protected String doInBackground(String... params) {
postsList.clear();
list.clear();
new Thread(new Runnable() {
public void run() {
//getting data from server and store into results
try {
array = new JSONArray(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < array.length(); i++) {
JSONObject row = null;
try {
row = array.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
unm = row.getString("Username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
postui = row.getString("Post");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = row.getString("Timestamp");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
idPost = row.getString("Id");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pst = unm + ":\n" + postui + "\n"
+ tmp.substring(0, tmp.length() - 2);
list.add(i, idPost);
postsList.add(createPost("post", pst));
}
runOnUiThread(new Runnable() {
#Override
public void run() {
lv.setSelector(R.drawable.row_pressed);
lv.setAdapter(simpleAdpt);
simpleAdpt.notifyDataSetChanged();
registerForContextMenu(lv);
}
});
}
}).start();
return null;
}
#Override
protected void onPostExecute(String unused) {
super.onPostExecute(unused);
simpleAdpt.notifyDataSetChanged();
progDailog.dismiss();
((PullToRefreshListView) lv).onRefreshComplete();
}
}
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
HashMap<?, ?> map = (HashMap<?, ?>) simpleAdpt
.getItem(aInfo.position - 1);
String string = (String) map.get("post");
menu.setHeaderTitle("Options");
menu.add(1, 1, 1, "Share via:");
menu.add(1, 2, 2, "Copy");
menu.add(1, 3, 3, "Delete");
menu.add(1, 1, 1, "Share via:");
menu.add(1, 2, 2, "Copy");
}
// This method is called when user selects an Item in the Context menu
#SuppressWarnings("deprecation")
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (itemId) {
case 1:
// Share intent
String key = ((TextView) info.targetView).getText().toString();
// create the send intent
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
// set the type
shareIntent.setType("text/plain");
// add a subject
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
R.string.app_name);
// build the body of the message to be shared
String shareMessage = key.substring(0, key.length() - 20)
.substring(key.indexOf(":") + 2);
// add the message
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
shareMessage);
// start the chooser for sharing
startActivity(Intent.createChooser(shareIntent, "Share via: "));
break;
case 2:
// Copy
String key1 = ((TextView) info.targetView).getText().toString();
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(key1.substring(0, key1.length() - 20)
.substring(key1.indexOf(":") + 2));
Toast.makeText(this, "Post copied.", Toast.LENGTH_SHORT).show();
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("", key1.substring(0, key1.length() - 20)
.substring(key1.indexOf(":") + 2));
clipboard.setPrimaryClip(clip);
Toast.makeText(this, "Post copied.", Toast.LENGTH_SHORT).show();
}
break;
case 3:
// Delete
int index = info.position - 1;
//deletes a post
deletePost(list.get(index), this);
new GetData().execute();
break;
}
return true;
}
My Logcat output
The content of the adapter has changed but ListView did not receive a
notification. Make sure the content of your adapter is not modified
from a background thread, but only from the UI thread.
You are using postList as content for your adapter. Then you change that content in doInBackground(). You cannot do that.
Here's what you have to do. Gather the data in doInBackground() and return it. The result will be passed to onPostExecute. Then, in onPostExecute, change the adapter content and notify about the data change. onPostExecute() runs in the UI thread.
If you want to periodically update your AdapterView, use publishProgress.
You don't need to start a new Thread in doInBackground and you don't need to invoke any runOnUIThread method. It will work (especially the runOnUIThread part) but then you don't need the AsyncTask class.