Starting AsyncTask in the onPostExecute - java

So here is how it is :
I have an AsyncTask with a TimerTask. Every 15 seconds the AsyncTask is run.
The AsyncTask gets XML data and put those in dynamically created TextView contained in dynamically create TableRow.
onPostExecute i create all my tableRow and TextView and then in order to not have them double instead of refresh i remove the tableRow views.
protected void onPostExecute(Document result)
{
if(TableLayout.getChildAt(1) == null)
{
//All my code to show tableRow and TextView
else
{
int u = 20;
while(tl.getChildAt(1) != null)
{
if(tl.getChildAt(u) != null)
tl.removeViewAt(u);
u--;
}
}
So yeah everything works just fine. I just want to know if there is some way to ask my TimerTask to restart right away instead of waiting x millis sec for timerTask so start again?
Thanks for your help!

So yeah i found out a way to do this. I'll post in case someone else wants to do something like that.
protected void onPostExecute(Document result)
{
if(tl.getChildAt(1) == null)
{
//do some code
}
else
{
int u = 20;
while(tl.getChildAt(1) != null)
{
if(tl.getChildAt(u) != null)
tl.removeViewAt(u);
u--;
}
//do same code over again as above.
}
}
}
This will delete the tableRows and recreate new ones thus "updating" them

Related

Buttons in android : Visible, Invisible, Gone

I am working on android app and need to define custom buttons.
Initially, I am setting the button to Invisible.
I want to execute a particular method, and check for a String value. If it returns null value, then the button should be still invisible. If it returns some string value, I want to invoke the button and perform some task then.
This is what I tried, but failing.
My app is crashing when the code value returns Null, with error : "attempt to invoke virtual method"
public String code = "";
Button startbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve_visits);
startbtn = findViewById(R.id.videobutton);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//code
}
});
//more code here
}
public void parseData(String response)
{
try {
JSONObject json = new JSONObject(response);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++)
{
JSONObject child = data.getJSONObject(i);
code = child.getString("code");
}
if(data.length()==0) ////check for empty array
startbtn.setVisibility(View.INVISIBLE);
else
startbtn.setVisibility(View.VISIBLE);
}
catch (Exception e) {
e.printStackTrace();
}
}
try the code below
if (code != null && !code.equels("")
{
startbtn.setVisibility(View.VISIBLE);
}
else
{
startbtn.setVisibility(View.GONE);
}
startbtn.setOnClickListener(new View.OnClickListener() {
//Required action
}
You can set a button in three ways in android:
1. VISIBLE
2. INVISIBLE
3. GONE
Use button.INVISIBLE to hide button instead of button.GONE as latter one removes button from view instead of hiding. This is the reason you are getting null pointer exception.
You may try the below code:
if (code == null || code.equals("")
{
startbtn.setVisibility(View.INVISIBLE);
}
else
{
startbtn.setVisibility(View.VISIBLE);
}
If the value in code is null or is empty, we set the button to invisible else it will be visible.

How to Force execution: button.setImageResource(R.drawable.x_sign)?

My ticTacToe Assigment picture
In onClickListener, I have line button00.setImageResource(R.drawable.x_sign);
but it will be executed only when listener is finished.
How can I force this command to execute immediately?
Condition in onClickListener for imageButton is:
if ((opField[x][y] == 0) && covekNext){ // field is empty and man have turn
button00.setImageResource(R.drawable.x_sign);
} else return;
When In this situation I play field 21 ( second row, first column).
button00.setImageResource(R.drawable.x_sign);
Images wouldnt be swaped! blank field stay blank, not X.
Bug or my coding error.
Thanks.
final ImageButton button00 = findViewById(R.id.imageButton00);
button00.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
x=0;
y=0;
if ((opField[x][y] == 0) && covekNext){
button00.setImageResource(R.drawable.x_sign);
} else return;
covekNext = false;
opField[x][y]= 1;
if(++opWinLines[0]==3|++opWinLines[3]==3|++opWinLines[6]==3){
covekWin(); //button00.setImageResource(R.drawable.x_sign); //command not executed
return;
}
if (++zauzeto<9) {
computerMove(); //button00.setImageResource(R.drawable.x_sign); //command not executed
} else {
nereseno(); //button00.setImageResource(R.drawable.x_sign); //command not executed
}
}
}); // button00.setImageResource(R.drawable.x_sign); executed
I think you are looking for something like this :
final ImageButton button00 = findViewById(R.id.imageButton00);
button00.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
x=0;
y=0;
if ((opField[x][y] == 0) && covekNext){
button00.setImageResource(R.drawable.x_sign);
} else return;
covekNext = false;
opField[x][y]= 1;
if(++opWinLines[0]==3|++opWinLines[3]==3|++opWinLines[6]==3){
button00.setImageResource(R.drawable.x_sign);
covekWin();
return;
}
if (++zauzeto<9) {
button00.setImageResource(R.drawable.x_sign);
computerMove();
} else {
button00.setImageResource(R.drawable.x_sign);
nereseno();
}
}
});
its because u use returnin your code
clicklisteners suppose to listen to clicks while user works with activity's ui
It works in most of cases but not always
You are only swapped the imageResource in first if condition. So when first else part is executed, image is not being swapped. If you want this line to execute every time, place it as first line in onClickListener as follows.
final ImageButton button00 = findViewById(R.id.imageButton00);
button00.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
x=0;
y=0;
//Set the imageResource here
button00.setImageResource(R.drawable.x_sign);
if ((opField[x][y] == 0) && covekNext){
} else return;
covekNext = false;
opField[x][y]= 1;
if(++opWinLines[0]==3|++opWinLines[3]==3|++opWinLines[6]==3){
covekWin();
return;
}
if (++zauzeto<9) {
computerMove();
} else {
nereseno();
}
}
});
Cheers :)
Everybody, thanks a lot!!!!
Everything about this question was my mistake made within some false call in methods: covekWin(); computerWin(); nereseno().
So this part of code is correct, and this question can be erased!
Thanks again!

How to pass more than one argument?

I am working on Android Studio 3.1.3.
My application consists of eight buttons. I am trying to pass more than one button as arguments from onClick method
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
pauseAudio(audioTwo, audioThree, audioFour, audioFive, audioSix, audioSeven, audioEight);
mediaPlayer = MediaPlayer.create(this,R.raw.birds);
mediaPlayer.start();
break;
to pauseAudio method,
public void pauseAudio(View view, Button audioOne, Button audioTwo, Button audioThree, Button audioFour, Button audioFive, Button audioSix, Button audioSeven, Button audioEight){
if(audioOne.isEnabled()
|| audioTwo.isEnabled()
|| audioThree.isEnabled()
|| audioFour.isEnabled()
|| audioFive.isEnabled()
|| audioSix.isEnabled()
|| audioSeven.isEnabled()
|| audioEight.isEnabled()){
if(mediaPlayer.isPlaying() && mediaPlayer!=null){
mediaPlayer.stop();
}
}
}
this is error it is showing when I hover over the underlined text
I am guessing the way I am passing argument is not the correct way, so please help me out. Thank you in advance.
To make your code easier and hopefully work, try this:
public void pauseAudio(View... views) {
for(View view : views) {
if(view.isEnabled()) {
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
break;
}
}
}
Now you can call it like this:
pauseAudio(audioOne, audioTwo, audioThree, ...);
EDIT:
Maybe also check if the view is not initialized:
if(view != null && view.isEnabled())
EDIT 2:
I'm glad to hear that it worked :) Here's a better explanation:
public void pauseAudio(View... views) { //Allow a dynamic initialization of an array of Views
for(View view : views) { //Loop through the array
if(view != null && view.isEnabled()) { //If the current view is not null and enabled
if(mediaPlayer!=null && mediaPlayer.isPlaying()){ //If the MediaPlayer is not null and playing
mediaPlayer.stop(); //Stop the MediaPlayer
}
break; //Break the loop, as we have reached our usecase
}
}
}
Maybe if you publish the log after crash we could help you better. but I already see a control that can crash
if (mediaPlayer.isPlaying () && mediaPlayer! = null) {
mediaPlayer.stop ();
}
. you could first check if mediaPlayer! = null before mediaPlayer.isPlaying () like this:
if (mediaPlayer! = null && mediaPlayer.isPlaying ()) {
mediaPlayer.stop ();
}

Dynamic List never Loading - Using parse.com

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.

how to preserve fragments recreation

I'm trying to implement a tab bar with fragments and RadioGroup
i switch fragments like on checked Change of radiogroup like this (saw something like this in sdk examples)
publi
void onCheckedChanged(RadioGroup radioGroup, int id) {
TabInfo newTab = mContent.get(id);
if (newTab != lastTab) {
FragmentTransaction transaction = mActivity.getSupportFragmentManager().beginTransaction();
if (lastTab != null && lastTab.fragment != null) {
transaction.detach(lastTab.fragment);
}
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(mActivity, newTab.getTag());
transaction.add(mContainerId, newTab.fragment);
} else {
transaction.attach(newTab.fragment);
}
lastTab = newTab;
transaction.setCustomAnimations(R.anim.tab_transaction, R.anim.tab_transaction);
transaction.commit();
}
}
but every time this happen attached fragment is created from scratch i.e. called onCreate and so on..
is there any way to preserve fragments from creating over and over again within an activity?
also i don't want the back button could switch fragments back;
Instead of using the methods FragmentTransaction.attach() and FragmentTransaction.detach() you could use FragmentTransaction.show() and FragmentTransaction.hide(). You would need to also alter some of the surrounding code you gave in the example above but I'll leave that as an exercise for your good-self.

Categories

Resources