populating RecyclerView from AsyncTask fails and results in empty Screen - android

Trying to populate data to a RecyclerView from cloud, though I get output in Main Thread, it takes time, so decided to add an AsyncTask to load items with ease and also to insert a ProgressDialog, however now it seems like code has no effect, getting an empty screen.
But the AsyncTask is getting executed, as I am able to log items in the logcat, no idea why I don't get a RecyclerView. Here is the code I use and looking for help:
public class BigBoard extends ActionBarActivity {
private List<Person> persons;
private RecyclerView rv;
private RVAdapter adapter;
private String a,b;
private ProgressDialog pr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "app-id", "client-key");
setContentView(R.layout.activity_big_board);
Loader abc = new Loader();
abc.execute();
adapter = new RVAdapter(persons);
rv=(RecyclerView)findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
}
private class Loader extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pr = new ProgressDialog(BigBoard.this);
pr.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pr.setIndeterminate(true);
pr.setCancelable(false);
pr.setMessage("Loading Board");
pr.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... urls) {
initializeData();
initializeAdapter();
return null;
}
#Override
protected void onPostExecute(String result) {
pr.dismiss();
}
private void initializeData(){
persons = new ArrayList<>();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("BigBoard");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> credentialList, ParseException e) {
if (e == null) {
for(int i=0;i<credentialList.size();i++)
{
a=credentialList.get(i).getString("Location");
b=credentialList.get(i).getString("Feed");
persons.add(new Person(a,b));
Log.d("OUT", "So the Val::------> " +a +b);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
adapter.notifyDataSetChanged();
}
});
}
private void initializeAdapter(){
rv.setAdapter(adapter);
}
}
}

place the adapter.notifyDataSetChanged(); or rv.setAdapter(adapter);
to onPostExecute..
since onOPostExecute works on UI Thread.
Edit :
create a function inside the Adapter
public void updatePersons(List<Person> persons) {
this.persons = persons;
notifyDataSetChanged();
}
after filling the list in onPostExecute call this function the List.

Related

doInBackground() method in an AsyncTask doesn't work when the activity is being re-opened

In my Android app, I have an activity which executes an AsyncTask<Void, Void, Void> named Scan using this code: new Scan().execute();.
In the onPreExecute() method, it starts a progress dialog, on the doInBackground(Void... voids) method it scans a table from DynamoDB, and on the onPostExecute(Void aVoid) method, it dismisses the progress dialog, and views the results of the DB scan in a ListView using a custom BaseAdapter class.
When I open the activity, everything runs great, but when I press the back button, and enter the activity again, then only the onPreExecute() and the onPostExecute(Void aVoid) methods are being executed, while doInBackground(Void... voids) isn't being executed, so it just shows and dismisses the progress dialog, and nothing else is being viewed on the screen.
How can I fix this?
Code:
MessagesListAdapter messages;
ListView messagesLv;
public static ArrayList<Message> arrayList;
public static ProgressDialog progressDialog;
public static DynamoDBScanExpression dbScanExpression;
public static List<Message> messageList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
new Scan().execute();
}
private class Scan extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(TestActivity.this);
progressDialog.setTitle(name);
progressDialog.setMessage("Searching for messages...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
dbScanExpression = new DynamoDBScanExpression();
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.EQ)
.withAttributeValueList(new AttributeValue().withS(MainActivity.msgId));
dbScanExpression.addFilterCondition("msgId", condition);
messageList = MainActivity.mapper.scan(Message.class, dbScanExpression);
arrayList = new ArrayList<Message>();
for (Message msg : messageList) {
if (msg.getUserId() == null || msg.getUserId().equals(MainActivity.userId)) {
msg.setMsgId(msg.getMsgId());
msg.setDate(msg.getDate());
msg.setTime(msg.getTime());
msg.setMessage(msg.getMessage());
msg.setUserId(msg.getUserId());
arrayList.add(msg);
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (!messageList.isEmpty()) {
messagesLv = (ListView) findViewById(R.id.messagesListView);
messages = new MessagesListAdapter(MinaActivity.this, arrayList);
messagesLv.setAdapter(messages);
progressDialog.dismiss();
} else {
TextView tv = (TextView) findViewById(R.id.noMessages);
tv.setVisibility(View.VISIBLE);
progressDialog.dismiss();
}
}
}
The reason that it couldn't find any messages, was that I checked if the user ID of the message equals to the user ID of the registered user. The problem was that it was taken from MainActivity.java which got it from an Intent extra, therefore, when I have left the activity, the variable has been erased.
What I did is to refer to the user ID from the SharedPreferences and suddenly it worked.
try to add messages.notifyDataSetChanged(); in onPostExecute() method.
or use below code
MessagesListAdapter messages;
ListView messagesLv;
public static ArrayList<Message> arrayList;
public static ProgressDialog progressDialog;
public static DynamoDBScanExpression dbScanExpression;
public static List<Message> messageList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
messagesLv = (ListView) findViewById(R.id.messagesListView);
messages = new MessagesListAdapter(MinaActivity.this, arrayList);
messagesLv.setAdapter(messages);
new Scan().execute();
}
private class Scan extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(TestActivity.this);
progressDialog.setTitle(name);
progressDialog.setMessage("Searching for messages...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
dbScanExpression = new DynamoDBScanExpression();
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.EQ)
.withAttributeValueList(new AttributeValue().withS(MainActivity.msgId));
dbScanExpression.addFilterCondition("msgId", condition);
messageList = MainActivity.mapper.scan(Message.class, dbScanExpression);
arrayList = new ArrayList<Message>();
for (Message msg : messageList) {
if (msg.getUserId() == null || msg.getUserId().equals(MainActivity.userId)) {
msg.setMsgId(msg.getMsgId());
msg.setDate(msg.getDate());
msg.setTime(msg.getTime());
msg.setMessage(msg.getMessage());
msg.setUserId(msg.getUserId());
arrayList.add(msg);
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (!messageList.isEmpty()) {
messages.notifyDataSetChanged();
progressDialog.dismiss();
} else {
TextView tv = (TextView) findViewById(R.id.noMessages);
tv.setVisibility(View.VISIBLE);
progressDialog.dismiss();
}
}
}

ProgressBar not showing in AsyncTask

I am loading list in ListView using AsyncTask by showing ProgressBar. But in my code the ProgressBar is now showing. Cant understand the problem.
I used the same code as in slidenerd but in the video code works but my code doesn't seem to work.
Video Link
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] items = {"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
listView.setAdapter(adapter);
new JSONTask().execute();
}
public class JSONTask extends AsyncTask<Void, String, Void> {
private ArrayAdapter<String> adapter;
private int count = 0;
#Override
protected void onPreExecute() {
adapter = (ArrayAdapter<String>) listView.getAdapter();
setProgressBarIndeterminateVisibility(true);
setProgressBarVisibility(true);
}
#Override
protected Void doInBackground(Void... params) {
for (String i : items) {
publishProgress(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
adapter.add(values[0]);
count++;
setProgress((int) (((double) count / items.length) * 10000));
}
#Override
protected void onPostExecute(Void aVoid) {
setProgressBarIndeterminateVisibility(false);
setProgressBarVisibility(false);
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
}
}
}
From the documentation of setProgressBarVisibility() and setProgressBarIndeterminateVisibility():
This method was deprecated in API level 24.
No longer supported
starting in API 21.
You should use a ProgressDialog instead.
you should use simple ProgressDialog
for example :
ProgressDialog myPd = ProgressDialog.show(context, "Please wait", "Uploading Database to Cloud...", true);
myPd.setCancelable(false);

Why is this implementation of parcelables to save and restore Custom Arraylist not Working

I am fetching data from json with Volley and populating RecyclerView with the parsed data but I ran into a bit of problem:
The call to get the items is in onCreate method, so the call is repeated each time the activity is recreated both from configuration changes and otherwise; hence the data is reloaded. So I found this answer that uses parcelables
and this article on Codepath (still on parcelables). After I have followed the instructions explicitly (or so I feel), there seems to be no change: the call to get data is repeated each time the activity is recreated.
FruitItems
public class FruitItems implements Parcelable {
private String fruit_title;
private String fruit_description;
private String fruit_image;
public String getFruit_title() {
return fruit_title;
}
public void setFruit_title(String fruit_title) {
this.fruit_title = fruit_title;
}
public String getFruit_description() {
return fruit_description;
}
public void setFruit_description(String fruit_description) {
this.fruit_description = fruit_description;
}
public String getFruit_image() {
return fruit_image;
}
public void setFruit_image(String fruit_image) {
this.fruit_image = fruit_image;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.fruit_title);
dest.writeString(this.fruit_description);
dest.writeString(this.fruit_image);
}
public FruitItems() {
}
protected FruitItems(Parcel in) {
this.fruit_title = in.readString();
this.fruit_description = in.readString();
this.fruit_image = in.readString();
}
public static final Parcelable.Creator<FruitItems> CREATOR = new Parcelable.Creator<FruitItems>() {
#Override
public FruitItems createFromParcel(Parcel source) {
return new FruitItems(source);
}
#Override
public FruitItems[] newArray(int size) {
return new FruitItems[size];
}
};
}
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private final String KEY_POST_ITEMS = "fruititems";
//List of fruits
private List<FruitItems> mFruitItemsList;
//Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.fruit_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_POST_ITEMS)) {
mFruitItemsList = savedInstanceState.getParcelableArrayList(KEY_POST_ITEMS);
} else {
//Initializing the fruitlist
mFruitItemsList = new ArrayList<>();
if (NetworkCheck.isAvailableAndConnected(this)) {
getData();
} else {
final Context mContext;
mContext = this;
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.alert_titl);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setIcon(R.mipmap.ic_launcher);
alertDialogBuilder.setMessage(R.string.alert_mess);
alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
adapter = new FruitAdapter(mFruitItemsList, this);
recyclerView.setAdapter(adapter);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList(KEY_POST_ITEMS, ArrayList<? extends Parcelable>))mFruitItemsList);
super.onSaveInstanceState(savedInstanceState);
}
//Getting json data
private void getData(){
Log.d(TAG, "getData called");
//Show progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_fruit));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigFruit.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//parsing json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
FruitItems fruitItem = new FruitItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
fruitItem.setFruit_title(jsonObject.getString(ConfigFruit.TAG_POST_TITLE));
fruitItem.setFruit_description(jsonObject.getString(ConfigFruit.TAG_POST_DESCRIPTION));
//Parsing image
JSONObject fruitImage = jsonObject.getJSONObject("thumbnail");
fruitItem.setFruit_image(fruitImage.getString("url"));
} catch (JSONException w) {
w.printStackTrace()
}
mFruitItemsList.add(fruitItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
}
I may not be a pro but I know that I have goofed somewhere in the codes above, else it should have worked.
Now, my question is where did I goof and how do I plug this mistake?
EDIT
I have edited the codes above to reflect the answer that I accepted. It works fine but there is still a problem.
I start Activity B from MainActivity. If I press the back-button in Activity B the data is saved but when I press the up-button, the getData is called again and the data is re-fetched.
Please, is there anyway around this?
You don't seem to have an onSaveInstanceState in your mainactivity. You need something like
#Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(KEY_POST_ITEMS,mFruitItemsList) ;
}
In order to retain your data for the activity that is about to be destructed and the one that is being created, you need to override the onSaveInstance callback
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList(KEY_POST_ITEMS, (ArrayList)mFruitItemsList);
super.onSaveInstanceState(savedInstanceState);
}
NOTE: always remember to call the superclass.

Listview does not automatically refresh after getting list data from DataStore

I have a ListView which I populate with data from DataStore or from my local database.
I am checking some condition that will determine whether I will fetch data from the DataStore or database. When I fetch from the database the ListView automatically refreshes itself, but when I fetch from the DataStore it does not. I then have to click my TextView, which is below ListView, and when I click it the soft keyboard appears and then my ListView is populated with data from DataStore.
My activity that has the ListView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xyz);
list_View = (ListView) findViewById(R.id.data_listView);
list_View.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
list_View.setMultiChoiceModeListener(new Selector());
adapter = new MyAdapter(context,Long.valueOf(id),isOnline());
list_View.setAdapter(adapter);
list_View.setSelection(adapter.getCount() - 1);
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
list_View.setSelection(adapter.getCount() - 1);
}
LoadDataTask ldt = new LoadDataTask();
ldt.execute("123456789");
}
private void loadDataFromDataStore(final Long contactId){
final ArrayList<Data> data = new ArrayList<>();;
d("loadingdataFromDatasore");
GetDataTask task = new GetDataTask(new ApiTask.ResultListener() {
#Override
public void successHook(Object o) {
if (o instanceof GetDataResponse) {
GetDataResponse res = (GetDataResponse) o;
if (res.getData() != null && res.getData().getItems() != null) {
for (ListDataItem i : res.getData().getItems()) {
Data dp = new Data(i.getPosition(), i.getMessage(), i.getDateCreated(),i.getMessageId(),1);
adapter.addFromOtherThread(dp);
}
}
d("Messages loaded from server: " + adapter.getCount());
}
}
}
public class LoadDataTask extends AsyncTask<String,String,Void> {
#Override
protected Void doInBackground(String... params){
if(isOnline && isFirstTime){
loadDataFromDataStore(Long.valueOf(params[0]));
}else{
//load from database
}
return null;
}
#Override
protected void onPostExecute(Void v){
adapter.notifyDataSetChanged();
}
}
My adapter class that extends BaseAdapter (I have removed unnecessary code for this question):
public class DataAdapter extends BaseAdapter {
private ArrayList<Data>data_list;
public DataAdapter(){
data_list = new ArrayList<>();
}
public void addFromOtherThread(Data object) {
data_list.add(object);
}
What am I missing that is making listview not to automatically refresh itself even after calling notifyDatasetChanged()?
change :
#Override
protected void onPostExecute(Void v){
adapter.notifyDataSetChanged();
}
}
to:
#Override
protected void onPostExecute(Void v){
adapter.notifyDataSetChanged();
list_View.setAdapter(adapter);
}
}
Let me know if more clarification is required by commenting below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xyz);
list_View = (ListView) findViewById(R.id.data_listView);
list_View.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
list_View.setMultiChoiceModeListener(new Selector());
adapter = new MyAdapter(context,Long.valueOf(id),isOnline());
list_View.setAdapter(adapter);
list_View.setSelection(adapter.getCount() - 1);
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
list_View.setSelection(adapter.getCount() - 1);
}
loadDataFromDataStore("123456789")
}
private void loadDataFromDataStore(final Long contactId){
final ArrayList<Data> data = new ArrayList<>();;
d("loadingdataFromDatasore");
new GetDataTask(new ApiTask.ResultListener() {
#Override
public void successHook(Object o) {
if (o instanceof GetDataResponse) {
GetDataResponse res = (GetDataResponse) o;
if (res.getData() != null && res.getData().getItems() != null) {
for (ListDataItem i : res.getData().getItems()) {
Data dp = new Data(i.getPosition(), i.getMessage(), i.getDateCreated(),i.getMessageId(),1);
adapter.addFromOtherThread(dp);
}
}
d("Messages loaded from server: " + adapter.getCount());
adapter.notifyDatasetChanges();
}
}
}.execute();
}
GetDataTask should work on background internally you don't need to starts a AsyncTask from here.
If you want to use AsyncTask then your AsyncTask should wait for the result from GetDataTask which it is not doing in your code implementation.
I don't know which kind of framework you are using to making api call but your implementation seems to look wrong.
I have write the code on assumption bases if your GetDataTask is a AsyncTask or some background processor it will work perfectly.

Java IO Exception Broken Pipe when attempting to populate listview with data from Parse.com

I am creating an Android application that runs three fragments that contain one listview in each. currently, I am trying to populate one of the listviews with content from a table that I created on Parse.com. I followed this tutorial: http://www.androidbegin.com/tutorial/android-parse-com-listview-images-and-texts-tutorial/ and applied it to work in my fragment. The problem is though, everytime I run my application, it loads the data for about 3 seconds and then suddenly crashes and gives me this error:
ddmlib: Broken pipe
java.io.IOException: Broken pipe
at sun.nio.ch.FileDispatcher.write0(Native Method)
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:29)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:69)
at sun.nio.ch.IOUtil.write(IOUtil.java:40)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:336)
at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
at com.android.ddmlib.Client.sendAndConsume(Client.java:642)
at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:348)
at com.android.ddmlib.Client.requestAllocationStatus(Client.java:488)
at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:835)
at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:803)
at com.android.ddmlib.DeviceMonitor.processIncomingJdwpData(DeviceMonitor.java:763)
at com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:652)
at com.android.ddmlib.DeviceMonitor.access$100(DeviceMonitor.java:44)
at com.android.ddmlib.DeviceMonitor$3.run(DeviceMonitor.java:580)
I have absolutely no idea why I am receiving this error. Here is the code from the fragment in which I am trying to populate my listview from. I am aslo using a custom adapter for the listview but I am using the same one from another project of mine so I am sure that is working fine. To fetch the data, I am calling new RemoteDataTask().execute(); in onCreateView . This is where I believe it is going wrong. I am also sure all my table names are correct in my parse database.
public class fraternitiesFragment extends Fragment {
private SwipeRefreshLayout swipeLayoutFraternities;
private ListView fratList;
List<ParseObject> objList;
ProgressDialog mProgressDialog;
fraternitiesAdapter fratAdapter;
private List<Frat> fraternitiesList = null;
public fraternitiesFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frat_fragment, null);
// Retrieve the SwipeRefreshLayout and ListView instances
swipeLayoutFraternities = (SwipeRefreshLayout)view.findViewById(R.id.swipe_refresh_fraternities);
swipeLayoutFraternities.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayoutFraternities.setRefreshing(false);
}
}, 3000);
}
});
// Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
swipeLayoutFraternities.setColorScheme(
R.color.tech_blue,
R.color.tech_gold,
R.color.tech_blue,
R.color.tech_gold);
new RemoteDataTask().execute();
return view;
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Loading Fraternities");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
fraternitiesList = new ArrayList<Frat>();
try{
ParseQuery<ParseObject> fraternitiesQuery = new ParseQuery<ParseObject>("Fraternities");
Log.i("Query", " Created");
fraternitiesQuery.orderByAscending("fratName");
objList = fraternitiesQuery.find();
for(ParseObject Fraternity : objList)
{
Frat fraternity = new Frat();
fraternity.setFratName((String) Fraternity.get("fratName"));
fraternity.setVoteCount((Integer) Fraternity.get("VoteCount"));
fraternitiesList.add(fraternity);
}
} catch (ParseException e)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
fratList = (ListView)getActivity().findViewById(R.id.frat_list);
fratAdapter = new fraternitiesAdapter(getActivity(), fraternitiesList);
Log.d("Adapter Created", "Created");
mProgressDialog.dismiss();
fratList.setAdapter(fratAdapter);
}
}
}
I really need help figuring out what is going wrong here that is leading to this Broken Pipe error. Any help or feedback is greatly appreciated!
Parse has already async methods, Try this
ParseQuery<ParseObject> query = ParseQuery.getQuery("Fraternities");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> fraternityList, ParseException e) {
// Do your work here
}
});

Categories

Resources