kamanzi abubakar kamanzi abubakar - 2 months ago 12
Android Question

AsynchTask and Firebase

I am trying to load a ListView using a RecyclerView , but only the progress bar is the one loading and the list is not showing . Am using Firebase in the AsyncTask class. Where am i going wrong, below is my code.

package huzykamz.jdhau.huzy.ask_doctor;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


import adapters.jdhau.me.NewsAdapter2;

import model.NewsModel;


public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {



public static String KEY_HEADLINES="headlines";
public static String KEY_DETAILS="details";


// private static final String TAG = "Ask Doctor App";

ProgressBar pb;


public List<NewsModel> newslist;

public NewsAdapter2 adapter;
private RecyclerView mRecyclerView;

private DatabaseReference mRef;
ImageView image_news;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// call the array list
newslist = new ArrayList<NewsModel>();

pb = (ProgressBar) findViewById(R.id.progressBarNews);
image_news =(ImageView) findViewById(R.id.image_news);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//Enabling offline capabilities
FirebaseDatabase.getInstance().setPersistenceEnabled(true);

// firebase initialisation......
mRef = FirebaseDatabase.getInstance().getReference("News");
// keep my data synced
mRef.keepSynced(true);


//firebase

//initializing async task
new MyTask();

// load data

//declare the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);



// ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo netInfo = cm.getActiveNetworkInfo();










FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* if (isOnline()) {

Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();
} else {
Snackbar.make(view, "There's a Network problem", Snackbar.LENGTH_LONG)
.setAction("", null).show();

}

Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();*/
}
});














DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}





public void LoadData (DataSnapshot dataSnapshot){




System.out.println(dataSnapshot.getValue());

NewsModel news_model =dataSnapshot.getValue(NewsModel.class);


newslist.add(news_model);

adapter = new NewsAdapter2(MainActivity.this, newslist);
mRecyclerView.setAdapter(adapter);




}

/* protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
*/




@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}

/*@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}*/

/* @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}*/

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Intent i;
if (id == R.id.hospitals) {

i = new Intent(MainActivity.this, HealthCentres.class);
startActivity(i);


} else if (id == R.id.doctors) {

i = new Intent(MainActivity.this, Doctors.class);
startActivity(i);


} /*else if (id == R.id.location) {
i = new Intent(MainActivity.this, Location.class);
startActivity(i);

} */else if (id == R.id.tips) {
i = new Intent(MainActivity.this, Tips.class);
startActivity(i);

} /*else if (id == R.id.faq) {


}
*/
/*
else if (id == R.id.suggestions) {

}
*/
else if (id == R.id.contacts) {
i= new Intent(MainActivity.this, ContactUs.class);
startActivity(i);

}
/*
else if (id == R.id.settings) {

}
*/
else if (id == R.id.about) {
i = new Intent(MainActivity.this, AboutUs.class);
startActivity(i);

}





DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}




private class MyTask extends AsyncTask<String,String,String>
{

@Override
protected void onPreExecute() {

pb.setVisibility(View.VISIBLE);
super.onPreExecute();
}


@Override
protected String doInBackground(String... params) {


mRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
LoadData(dataSnapshot);
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
LoadData(dataSnapshot);
}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

return null;
}

@Override
protected void onPostExecute(String s) {
pb.setVisibility(View.INVISIBLE);
super.onPostExecute(s);
}
}















}

Answer

Firebase has already it's Asynchronous litsener , so what you can do put this in the onCreate Method. But you said that the progress bar is the only visible , just also add this code of line in the onChildEventLitsener() method pb.setVisibility(View.INVISIBLE);, so that when data comes the Progress bar dissapears.

mRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                pb.setVisibility(View.INVISIBLE);
                LoadData(dataSnapshot);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                LoadData(dataSnapshot);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

Hope this works well.