Dynamic List never Loading - Using parse.com - java

SEE REVISION AT BOTTOM This is a fight card, so it has two people fighting one another, a red vs blue. It has to be a dynamic list that is populated information from parse.com. The first Query is fightOrder. This is a class on Parse.com that has two objectId's on a row. The redCorner and blueCorner find this information in my database (also on parse.com) and display the information accordingly. My problem, is my progressDialog box appears, and it never goes away. My list is never populated. I tried doing it without the dialog box, and populating my list with ever query and had same results.
NOTE: the list is working properly. This is a list I have used successfully before when I would load my information differently. I am just changing the way I load information because I need to have a database of all fighters, and load my fight card from that list.
NOTE: GetCallBack and FindCallBack are asynchronous, that is why this is an odd loop. I have to wait for the done().
Here is the java
public class databaseFightCard extends Activity {
int I;
int size;
private HomeListAdapter HomeListAdapter;
private ArrayList<HomeItem> HomeItemList;
private SeparatedListAdapter adapter;
//this int is to test for main and coMain events. If one is TRUE, It will assign the array position to main or coMain.
int main, coMain;
ParseQuery<ParseObject> blueCorner = ParseQuery.getQuery("FightersDB");
ParseQuery<ParseObject> redCorner = ParseQuery.getQuery("FightersDB");
String name1, name2;
List<String> red = new ArrayList<String>();
List<String> blue = new ArrayList<String>();
private ListView listView;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_list);
progressDialog = ProgressDialog.show(this, "", "Loading bout...", true);
initialization();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
AlertDialog.Builder showFighter = new AlertDialog.Builder(databaseFightCard.this, android.R.style.Theme_DeviceDefault_Dialog);
showFighter.setTitle(homeItem.getHomeItemLeft().toString() + " and " + homeItem.getHomeItemRight().toString());
showFighter.setMessage("166 - 165\nLogan Utah - Richmond Utah");
showFighter.setPositiveButton("DONE", null);
showFighter.setNegativeButton("Cancel", null);
AlertDialog dialog = showFighter.show();
TextView messageView = (TextView) dialog.findViewById(android.R.id.message);
messageView.setGravity(Gravity.CENTER);
Toast.makeText(getBaseContext(), homeItem.getHomeItemLeft().toString() + " " + homeItem.getHomeItemRight().toString(), Toast.LENGTH_LONG).show();
System.out.println("Selected Item : " + homeItem.getHomeItemID());
}
});
HomeListAdapter = new HomeListAdapter(getApplicationContext(), 0, HomeItemList);
//find the fight card, and read the ids
ParseQuery<ParseObject> fightOrder = ParseQuery.getQuery("FightCard");
fightOrder.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if (e == null) {
size = parseObjects.size();
int i = 0;
while (i < size) {
if (parseObjects.get(i).getBoolean("main")) {
main = i;
}
if (parseObjects.get(i).getBoolean("coMain")) {
coMain = i;
}
red.add(i, parseObjects.get(i).getString("redCorner"));
blue.add(i, parseObjects.get(i).getString("blueCorner"));
i++;
}
displayRed();
} else {
e.printStackTrace();
}
}
});
}
private void displayRed() {
adapter = new SeparatedListAdapter(this);
//find one fighter at a time. in the done() method, start the second fighter.
redCorner.getInBackground(red.get(I), new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
HomeItemList = new ArrayList<HomeItem>();
HomeItem homeItem = new HomeItem();
homeItem.setHomeItemID(I);
name1 = parseObject.getString("Name");
homeItem.setHomeItemLeft(name1);
HomeItemList.add(homeItem);
if (HomeListAdapter != null) {
if (I == main) {
adapter.addSection(" MAIN EVENT ", HomeListAdapter);
} else if (I == coMain) {
adapter.addSection(" Co-MAIN EVENT ", HomeListAdapter);
} else {
adapter.addSection(" FIGHT CARD ", HomeListAdapter);
}
}
displayBlue();
} else {
e.printStackTrace();
}
I++;
while (I < size){
displayRed();
}
if (size == I) {
listView.setAdapter(adapter);
progressDialog.dismiss();
}
}
});
}
private void displayBlue() {
//find the red fighters then call the dismiss();
blueCorner.getInBackground(blue.get(I), new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
HomeItemList = new ArrayList<HomeItem>();
HomeItem homeItem = new HomeItem();
homeItem.setHomeItemID(I);
name2 = parseObject.getString("Name");
homeItem.setHomeItemLeft(name2);
HomeItemList.add(homeItem);
if (HomeListAdapter != null) {
if (I == main) {
adapter.addSection(" MAIN EVENT ", HomeListAdapter);
} else if (I == coMain) {
adapter.addSection(" Co-MAIN EVENT", HomeListAdapter);
} else {
adapter.addSection(" FIGHT CARD ", HomeListAdapter);
}
}
} else {
e.printStackTrace();
}
//if it is done running through all the IDS, set the listView, and dismiss the dialog.
I++;
while (I < size){
displayRed();
}
if (size == I) {
listView.setAdapter(adapter);
progressDialog.dismiss();
}
}
});
}
private void initialization() {
listView = (ListView) findViewById(R.id.Listview);
}
LogCat
java.lang.RuntimeException: This query has an outstanding network
connection. You have to wait until it's done.
That is pointing to this line:
while (I < size){
displayRed();
}
EDIT
I believe that it is the async tasks that are causing this.
On a previous build: I would call for one line item at a time, add it to my list, repeat until finished, then display list.
On the this build: I want to call for redCorner add it to my list, call blueCorner add it to the same line, repeat until finished, then display the list. Here is what it would look like (previous build):
Revised My question is still unanswered. Maybe I need to simplify it. I will have +-20 objectId's from one class. I took out all the code that is irrelevant. Still getting unexpected results with this code.
redCorner.getInBackground(red.get(i), new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
Log.d("NAME " + i, name1 + " ");
i++;
while (i < size) {
redCorner.cancel();
displayRed();
}
if (i == size) {
progressDialog.dismiss();
}
} else {
e.printStackTrace();
}
}
});

This is yet another case of not understanding the nature of Async coding (I've seen a lot of questions with the same issue).
In your case you are calling the displayRed() method that fires off some async code, then returns.
Here's how your code might run:
First call to displayRed() (dr1)
(dr1) Async redCorner.getInBackground(..) (async1) started
(dr1) returns
.. some time passes ..
(async1) getInBackground(..) call returns with data, runs code block
calls displayBlue() (db1)
(db1) blueCorner.getInBackground(..) (async2) started
(db1) returns
begins the while loop
calls displayRed() (dr2)
(dr2) Async redCorner.getInBackground(..) (async3) started
(dr2) nothing has touched I yet, tries to start another async redCorner.getInBackgroud(..) (async4)
ERROR
You're writing your code as if the async blocks are running sync instead. Keep in mind that getInBackground means "make a web call to get this data, and when something happens (error or success) run this block of code I'm giving you, possibly on another thread".
Think about the order you want to achieve things, realise that you're asking it to start a process that takes some time, and adjust your code accordingly.

Related

How To Change ImageView drawable For A Single RecyclerView Row

I am not particularly sure how to ask this question, so I will just use images to explain
In my App, onClick of the download icon calls a download method for the video in the row. When it is completely downloaded, the Icon changes from black to green. A boolean flag is used to save this state in SharedPreference. This saved state is called again in my RecyclerView Adapter so the downloaded state can reflect when the app is relaunched.
THE CHALLENGE IS...
When the app relaunches, instead only the downloaded row icon to show green, the Icon turns green for every row even when they have not been downloaded. below is my code.
class DownloadReceiver extends ResultReceiver { //DownloadReceiver class
public DownloadReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == TichaDownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
//Set the progress to progressBarCir
progressBarCir.setProgress(progress);
icon_download.setVisibility(View.GONE);
progressBarCir.setVisibility(View.VISIBLE);
Log.i("STATUS", "DOWNLOADING>>>");
if (progress == 100) { // Downloade process is completed
isNotDownloaded = false; // Flagging that the video has been downloaded
progressBarCir.setVisibility(View.GONE);
// Setting the Download Icon to reflect the New color state
icon_download.setColorFilter(itemView.getContext().getResources().getColor(R.color.funnygreen));
icon_download.setVisibility(View.VISIBLE);
// Saving the boolean flag in SharedPreferece
SharedPreferences sharedPreferences = getSharedPreferences("com.example.instagramclone",MODE_PRIVATE);
sharedPreferences.edit().putBoolean("isDownloadedState",isNotDownloaded).commit();
// Logging of the save state to confirm state is saved.
boolean newState= sharedPreferences.getBoolean("isDownloadedState",true);
Log.i("STATE XCHANGE", "DOWNLOADED HENCE, "+String.valueOf(newState));
}
} else {
Log.i("STATUS", " NOT DOWNLOADING,BOSS");
}
}
}
Below is a snippet of Holder section of my Adapter Class
public LectureClassesHolder(#NonNull final View itemView) {
super(itemView);
// Now we ref each custom layout view item using the itemView
textViewTitle = itemView.findViewById(R.id.subject_topic);
textViewDescription = itemView.findViewById(R.id.subject_description);
textViewDuration = itemView.findViewById(R.id.subject_duration);
imageViewDownload = itemView.findViewById(R.id.download);
textViewUrl = itemView.findViewById(R.id.url_link);
SharedPreferences sharedPreferences = itemView.getContext().getSharedPreferences("com.example.instagramclone",Context.MODE_PRIVATE);
isNotDownloaded = sharedPreferences.getBoolean("isDownloadedState",true);
if (isNotDownloaded){
imageViewDownload.setColorFilter(itemView.getContext().getResources().getColor(R.color.black));
Log.i("DOWNLOAD STATE ","NOT Downloaded State is "+ isNotDownloaded);
}else {
imageViewDownload.setColorFilter(itemView.getContext().getResources().getColor(R.color.funnygreen));
Log.i("DOWNLOAD STATE ","NOT Downloaded State is "+ isNotDownloaded);
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && listener != null) {
listener.onItemClick(getSnapshots().getSnapshot(position), position, itemView);
}
}
});
// Incase e no work
imageViewDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && listener != null) {
listener.onViewItemClick(getSnapshots().getSnapshot(position), position, itemView);
}
}
});
}
I NEED a way to make the change effective for only the row concerned. Would appreciate any assistance on how to achieve this.
The problem is there is of course no association between the individual records and what is stored .The best solution would be to use a database with a table containing atleast a column for the download url and another for status,store the records with the desired status (for example use 0 for not downloaded status and 1 for downloaded status ) and update status column of the row with your url after download then you can query to check the status of the record .however a quick fix to your solution while still using shared prefrence would be to store the links in an array and check against that array see:
public static String all_records(Context act)
{
SharedPreferences prefs = act.getSharedPreferences("SHARED_PREFS_NAME", act.MODE_PRIVATE);
return prefs.getString("all_records", "[]");
}
public static void add_download(Activity act,String url)
{
JSONArray ja=new JSONArray();
try {
ja=new JSONArray(all_records(act));
JSONObject jo=new JSONObject();
jo.put("url",url);
ja.put(jo);
} catch (JSONException e) {
e.printStackTrace();
}
SharedPreferences.Editor saver =act.getSharedPreferences("SHARED_PREFS_NAME", act.MODE_PRIVATE).edit();
saver.putString("all_records",ja.toString());
saver.commit();
}
public static boolean is_downloaded(Activity act,String url)
{
JSONArray ja=new JSONArray();
try {
ja=new JSONArray(all_records(act));
for (int i=0;i<ja.length();i++)
{
try {
Log.e("Check ", "" + ja.getJSONObject(i).getString("url") + " Against " + url);
if (ja.getJSONObject(i).getString("url").equalsIgnoreCase(url)) {
return true;
}
}catch (Exception ex){}
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
in this case you would use it like this to when downloading
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == TichaDownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
//Set the progress to progressBarCir
progressBarCir.setProgress(progress);
icon_download.setVisibility(View.GONE);
progressBarCir.setVisibility(View.VISIBLE);
Log.i("STATUS", "DOWNLOADING>>>");
if (progress == 100) { // Downloade process is completed
isNotDownloaded = false; // Flagging that the video has been downloaded
progressBarCir.setVisibility(View.GONE);
// Setting the Download Icon to reflect the New color state
icon_download.setColorFilter(itemView.getContext().getResources().getColor(R.color.funnygreen));
icon_download.setVisibility(View.VISIBLE);
// Saving the boolean flag in SharedPreferece
add_download(/*your context*/,/*your url*/);
}
} else {
Log.i("STATUS", " NOT DOWNLOADING,BOSS");
}
}
on your recycle view adapter onbindview or wherever you want to get retrieve the status of whether downloaded call is_downloaded(/*YOUR CONTEXT*/,"YOUR URL");

Unable to use Handler properly

I started learning Android Development. I was building a basic addition game, where user has to click on button which shows the addition of two number. There are four Textviews. First one give the time limit for each question to answer. Second gives the question for the user. Third one gives the current score of the user and the last one gives whether the chosen open is correct or incorrect.
Everything is working except the First Button. Every time when the button is pressed the the counting takes very fast.
// When First button is pressed
public void onClickButton1(View view) {
correctIncorrect.setVisibility(View.VISIBLE);
if (Integer.parseInt(button1.getText().toString())==sum) {
correctIncorrect.setText("Correct");
correctUpdater();
}
else {
correctIncorrect.setText("Incorrect");
inCorrectUpdater();
}
}
//Similar to all the buttons
//To Update the score
public void correctUpdater() {
n++;
yourScore++;
score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));
update();
}
public void inCorrectUpdater() {
n++;
score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));
update();
}
// To update the timer
//=======================================================================//
public void resetTimer() {
timer.setText(Integer.toString(temp)+"s");
if (temp == 0) {
inCorrectUpdater();
update();
}
else {
timeUpdater();
}
}
public void timeUpdater() {
Handler timeHandler = new Handler();
Runnable timeRunnable = new Runnable() {
#Override
public void run() {
temp--;
resetTimer();
}
};
timeHandler.postDelayed(timeRunnable,1000);
}
//=================================================================//
// Updater function
public void update() {
correctIncorrect.setVisibility(View.INVISIBLE);
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
question.setText(Integer.toString(a) + " + " + Integer.toString(b));
Log.i("info", "onCreate: a = " + a);
Log.i("info", "onCreate: b = " + b);
sum = a+b;
Log.i("info", "onCreate: sum = " + sum);
int whichButton = random.nextInt(4);
Log.i("info", "onCreate: random button is " + whichButton);
values.clear();
for (int i = 0; i< 4; i++) {
if (i == whichButton) {
values.add(sum);
}
else {
values.add(random.nextInt(50));
}
Log.i("info", "onCreate: value[" + i + "] = " + values.get(i));
}
button1.setText(Integer.toString(values.get(0)));
button2.setText(Integer.toString(values.get(1)));
button3.setText(Integer.toString(values.get(2)));
button4.setText(Integer.toString(values.get(3)));
temp = 10;
resetTimer();
}
Am I using the Handler incorrectly? What can I do?
Am I using the Handler incorrectly? What can I do?
A better way to do this is CountDownTimer, by using this you won't have to deal with Handler youself and you also have a provision to cancel a running CountDownTimer.
Everything is working except the First Button
Not really sure what can cause different behaviours on click of buttons with the same code in onClick(). But you can consider using the same onClickListener for all the 4 buttons, in this way :
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View button) {
correctIncorrect.setVisibility(View.VISIBLE);
if (Integer.parseInt(button.getText().toString())==sum) {
correctIncorrect.setText("Correct");
correctUpdater();
}
else {
correctIncorrect.setText("Incorrect");
inCorrectUpdater();
}
}
};
button1.setOnClickListener(myListener);
button2.setOnClickListener(myListener);
button3.setOnClickListener(myListener);
button4.setOnClickListener(myListener);
This will ensure that clicking any of the 4 buttons will have a same behavior (depending on the answer of course)
In case you get confused with the onTick() method on CountDownTimer, you can use modified CountDownTimer which will ensure that the timer doesn't miss any ticks.

RecyclerView is scrolling to up automatically and flickering

Basically I'm using a RecyclerView with gridAdapter to load images from server. But the problem is items of RecyclerView are blinking in a quirky manner. I've tried all the possible solutions but none of them worked so far.
I tried to update glide version from 4.4.0 to 4.8.0 but it's futile. I also tried to disable the animations of RecyclerView but that couldn't help. Can anyone please help me to solve this issue?
Code:
GridLayoutManager gridLayoutManager = new GridLayoutManager(v.getContext(),3);
gridLayoutManager.setSmoothScrollbarEnabled(true);
gridLayoutManager.setItemPrefetchEnabled(true);
gridLayoutManager.setInitialPrefetchItemCount(20);
posts_rView.setLayoutManager(gridLayoutManager);
posts_rView.setItemAnimator(null);
posts_rView.setHasFixedSize(true);
gridPostAdapter=new StarredAdapter(timelineDataList);
posts_rView.setAdapter(gridPostAdapter);
Data Updation Code:
private Emitter.Listener handlePosts = new Emitter.Listener(){
#Override
public void call(final Object... args){
try {
JSONArray jsonArray=(JSONArray)args[0];
Needle.onMainThread().execute(() -> {
timelineDataList.clear();
swipeRefreshLayout.setRefreshing(false);
for(int i=0;i<jsonArray.length();i++){
try {
//JSONArray arr=jsonArray.getJSONArray(i);
JSONObject ob=jsonArray.getJSONObject(i);
post_username=ob.getString("_pid");
post_fullname=ob.getString("owner_fullname");
if(ob.has("owner_profPic"))post_profPic=ob.getString("owner_profPic");
else post_profPic="";
post_time=ob.getString("time");
post_link=ob.getString("img_link");
likes_counter=ob.getString("likes_counter");
comments_counter=ob.getString("comments_counter");
if(ob.has("caption")) post_caption=ob.getString("caption");
else post_caption=null;
//Skipping Private Posts
if(ob.getString("private_post_stat").equals("yes")&&!post_username.equals(my_username)) {
continue;
}
else
private_post_stat = ob.getString("private_post_stat");
comment_disabled=ob.getString("comment_disabled");
share_disabled=ob.getString("share_disabled");
download_disabled=ob.getString("download_disabled");
if(ob.has("short_book_content")) short_book_content=ob.getString("short_book_content");
else short_book_content=null;
society_name_adp=ob.getString("society");
addTimelineData(post_username,post_fullname,post_profPic,post_time,post_link,post_caption,
private_post_stat,comment_disabled,share_disabled,download_disabled,likes_counter,comments_counter,short_book_content,society_name_adp);
} catch (JSONException e) {
e.printStackTrace();
}
}
RecyclerView.Adapter adapter=posts_rView.getAdapter();
posts_rView.setAdapter(null);
posts_rView.setAdapter(adapter);
});
} catch (Exception e) {
Log.e("error",e.toString());
}
}
};
private void addTimelineData(String username,String fullname,String post_profPic,String time,String img_link,String caption,
String private_post_stat,String comment_disabled,String share_disabled,String download_disabled,String likes_counter,
String comments_counter,String short_book_content,String society_name_adp){
boolean isRepeated = false;
for(TimelineData data:timelineDataList){
if (data.getTime().equals(time)) {
isRepeated = true;
}
}
if(!isRepeated){
timelineDataList.add(new TimelineData(username,fullname,post_profPic,time,img_link,caption,private_post_stat,comment_disabled,share_disabled,download_disabled,likes_counter,comments_counter,short_book_content,society_name_adp));
gridPostAdapter.notifyDataSetChanged();
// posts_rView.scrollToPosition(gridPostAdapter.getItemCount()-1);
// posts_rView.scrollToPosition(0);
}
//gridPostAdapter.notifyItemInserted(timelineDataList.size()-1);
}
Adapter Class:
#Override
public void onBindViewHolder(StarViewHolder holder, int position) {
//loading img
Glide.with( parent.getContext()).asBitmap().load(arrayList.get(position)).apply(new RequestOptions()
.override(200, 200)
.dontAnimate()
.placeholder(new ColorDrawable(Color.parseColor("#20001919"))))
.thumbnail(0.1f)
.into(holder.img);
}
#Override
public int getItemCount() {
return arrayList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
I do not quite understand yet why the flickering and repositioning to the first element is occurring in your case, as I do not see the updating policy of your RecyclerView. However, I would like to suggest something which might remove the problem.
I would like to suggest you remove the setInitialPrefetchItemCount and setItemPrefetchEnabled configurations while setting GridLayoutManager. This will aid in case of you are having a nested RecyclerView which is not your case.
You are setting adapter each time you are updating your data from the server. I guess you are calling the update action code when you are scrolling the items. Which you should not. Moreover, please remove setting up the adapter of your RecyclerView each time you are updating the dataset. Just use, notifyDataSetChanged after each of your updates. Do not clear the timelineDataList and append the new items instead, and then call notifyDataSetChanged on your adapter.
You are calling notifyDataSetChanged in addTimelineData after each insert to your list. This should be done only after adding all the elements to the list.
So I would like to propose the following code for setting your adapter and updating your RecyclerView. Please note that I have not tested the code and you might have to modify some errors which might occur.
The code for setting up the layout manager and the adapter.
GridLayoutManager gridLayoutManager = new GridLayoutManager(v.getContext(),3);
posts_rView.setLayoutManager(gridLayoutManager);
posts_rView.setHasFixedSize(true);
gridPostAdapter = new StarredAdapter(timelineDataList);
posts_rView.setAdapter(gridPostAdapter);
The code for updating the list.
private Emitter.Listener handlePosts = new Emitter.Listener(){
#Override
public void call(final Object... args){
try {
JSONArray jsonArray = (JSONArray)args[0];
Needle.onMainThread().execute(() -> {
// Do not clear the list. Just append the new data in the list instead
// timelineDataList.clear();
swipeRefreshLayout.setRefreshing(false);
for(int i = 0; i < jsonArray.length(); i++){
try {
JSONObject ob = jsonArray.getJSONObject(i);
post_username = ob.getString("_pid");
post_fullname = ob.getString("owner_fullname");
if(ob.has("owner_profPic")) post_profPic = ob.getString("owner_profPic");
else post_profPic = "";
post_time = ob.getString("time");
post_link = ob.getString("img_link");
likes_counter = ob.getString("likes_counter");
comments_counter = ob.getString("comments_counter");
if(ob.has("caption")) post_caption = ob.getString("caption");
else post_caption = null;
//Skipping Private Posts
if(ob.getString("private_post_stat").equals("yes")&&!post_username.equals(my_username)) {
continue;
}
else
private_post_stat = ob.getString("private_post_stat");
comment_disabled = ob.getString("comment_disabled");
share_disabled = ob.getString("share_disabled");
download_disabled = ob.getString("download_disabled");
if (ob.has("short_book_content")) short_book_content = ob.getString("short_book_content");
else short_book_content = null;
society_name_adp = ob.getString("society");
addTimelineData(post_username, post_fullname, post_profPic, post_time, post_link,post_caption, private_post_stat, comment_disabled, share_disabled, download_disabled, likes_counter, comments_counter, short_book_content, society_name_adp);
} catch (JSONException e) {
e.printStackTrace();
}
}
gridPostAdapter.notifyDataSetChanged();
});
} catch (Exception e) {
Log.e("error",e.toString());
}
}
};
private void addTimelineData(String username, String fullname, String post_profPic, String time, String img_link, String caption, String private_post_stat, String comment_disabled, String share_disabled, String download_disabled, String likes_counter, String comments_counter, String short_book_content, String society_name_adp) {
boolean isRepeated = false;
for(TimelineData data:timelineDataList){
if (data.getTime().equals(time)) {
isRepeated = true;
}
}
if(!isRepeated){
timelineDataList.add(new TimelineData(username,fullname,post_profPic,time,img_link,caption,private_post_stat,comment_disabled,share_disabled,download_disabled,likes_counter,comments_counter,short_book_content,society_name_adp));
// Do not call notifyDataSetChanged each time you are adding an item. This will be called in the call function above. So remove this line.
// gridPostAdapter.notifyDataSetChanged();
}
}
Try to add some pagination in the server side API if it is not there already so that you might fetch the next 20 dataset instead of fetching the whole data again when you are scrolling down.
Hope that helps.

Edit text parsing integer android

I am making android app and I have edit text surrounded by two buttons for increase and decrease
and when I click the button increase or decrease for the first time it did not work but it start working from the second time
e.g if the number in edit text field is 50 when I press increase it still 50 when I press increase again it change to 51 and again it change to 52 and so on
here is my java code for the two buttons
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (quantityEdit.getText().toString().equals("") || quantityEdit.getText().toString() == null) {
quantityEdit.setText("0");
} else {
int a = Integer.parseInt(quantityEdit.getText().toString());
int b = a + 1;
quantityEdit.setText(String.valueOf(b));
}
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int a = Integer.parseInt(quantityEdit.getText().toString());
if (a >= 1) {
int b = a - 1;
quantityEdit.setText(String.valueOf(b));
} else {
quantityEdit.setText("0");
}
}
});
It looks like you are checking for empty string or null in "add", but not in "sub". As Michael Krause said, you should use TextUtils.isEmpty(), and set a default value before performing add or sub operations.
If you are setting a default value elsewhere, please show your code.
Consider refactoring your code like so
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quantityEdit.setText(String.valueOf(getIntVal(quantityEdit) + 1));
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int value = getIntVal(quantityEdit);
if (value > 0) {
value--;
}
quantityEdit.setText(String.valueOf(value));
}
});
// helper method to get the integer value of a TextView
private int getIntVal(TextView textView) {
CharSequence rawValue = textView.getText();
int value;
if (!TextUtils.isEmpty(rawValue)) {
try {
value = Integer.parseInt(rawValue.toString());
} catch (NumberFormatException e) {
value = 0;
// TODO log / notify user
}
} else {
value = 0;
}
}
This way your initialization is handled in one place and it's more clear.
In any event, your first condition is wrong. You do a null check after trying to access the object (it's backwards). Have you checked your logs? This could throw an exception for a null value and "lose" the first click.

Wait on multiple dialog inputs before processing data using Runnables

I thought I'd figured out this problem, by making a function showMessage, which can take a Runnable as an argument and run that piece of code if that particular button has been pressed.
Now I find the problem that I need to wait on several inputs before running the code. I essentially go through a bunch of questions which are added dynamically, so I don't know how many there'll be. When the users presses "Submit", it checks if any that are "soft" required and if there's no answer pops up with the message "There isn't an answer, would you like to continue anyway?".
The way I thought I could handle this is by counting the amount of questions which are like that, assigning them an Enumerator with a boolean variable to say if they're INPROGRESS or COMPLETE. I then had the Runnable to set that particular question's Progress state to COMPLETE and if they click "No", then to set the boolean variable to false.
Since the the dialogs are launched asynchronously, I can't just do an if statement, so I did a while any were still in progress. Buuuuuut! When I click submit now, it just freezes. I'm guessing because it's stuck at the while loop, whilst also not launching the dialogs asynchronously. I think it has to "complete" the code before launching them?
My code for reference to the points made above, this is all in the onClick of the submit button:
//Prep work
final ArrayList<Result> results = new ArrayList<Result>();
for (BaseQuestion q : questionViews)
{
if (q.requiredSoft)
{
results.add(Result.INPROGRESS);
}
}
final int[] i = {0};
//Validation checks
Boolean allOk = true;
for (BaseQuestion questionView : questionViews)
{
if (questionView.isRequiredHard())
{
if (questionView.getResponse().isEmpty())
{
Utils.showMessage("You have to fill in '" + questionView.getQuestionText() + "'", v.getContext());
allOk = false;
break;
}
}
else if (questionView.isRequiredSoft())
{
if (questionView.getResponse().isEmpty())
{
Runnable isOk = new Runnable()
{
#Override
public void run()
{
results.get(i[0]).value = 1;
results.get(i[0]).result = true;
i[0]++;
}
};
Runnable isNotOk = new Runnable() {
#Override
public void run() {
results.get(i[0]).value = 1;
i[0]++;
}
};
Utils.showMessage("You've not filled in '" + questionView.getQuestionText() + "'. Do you wish to continue?", v.getContext() , isOk, "Yes", isNotOk, "No");
}
}
else
{
}
}
if (allOk)
{
for (Result result : results)
{
while (result == Result.INPROGRESS)
{
}
if (!result.result)
{
allOk = false;
}
}
if (allOk)
{
submitQuestionnaire();
}
}
you can put all soft check into a runnable linkļ¼Œ and do the submit action at the last runnable. I not have a IDE now, see following logic
on submit button clicked{
allOk = true;
foreach(question in questions){
if(question require hard && question is empty){
allOk = false;
break;
}
}
if(allOk){
boolean needMoreConfirm = false;
for(int i = 0; i < questions.length; i++){
if(question require soft && question is empty){
Runnable isOk = new MyRunnable(i + 1, questions);/*begin check from next question*/
Utils.showMessage("your question",
new MyRunnable(i + 1)/* check next soft */,
null/*do nothing, wait another submit click*/);
needMoreConfirm = true;
break;
}
}
if(!needMoreConfirm){
do real submit here
}
}
}
class MyRunnable extends Runnable{
protected int mIdx;
Question[] mQuestions;
public MyOkRunnalbe(int idx, Question[] qs){mIdx = idx; mQuestions = qs;}
public void run(){
boolean needMoreConfirm = false;
for(int i = mIdx; i < questions.length; i++){
if(mQuestions[i] is empty && mQuestions[i] is soft){
Utils.showMessage("your question",
new MyRunnable(i + 1)/* begin to check from next soft */,
null/*do nothing, wait another submit click*/);
needMoreCOnfirm = true;
break;
}
}
if(!needMoreConfirm){
do real submit here
}
}
}
SOLVED
If I gave myself another half an hour to tinker, would've been fine! I whacked the checking code in a separate thread, this means it wasn't hanging.
But then I had the problem of the result not changing state. So instead of doing my for loop as a for each item loop, I did it as an index, as it wasn't changing the state when it kept checking.
As shown below:
new Thread(new Runnable() {
#Override
public void run() {
if (allOk[0])
{
for (int i=0; i<results.size(); i++)
{
while (results.get(i) == Result.INPROGRESS)
{
}
if (!results.get(i).result)
{
allOk[0] = false;
}
}
if (allOk[0])
{
submitQuestionnaire();
}
}
}
}).start();

Categories

Resources