ProgressBar is getting invisible before load map completely - java

I'm loading my markers(clustering) from a json and it's working.
But the markers is not so fast to render. My solution is show the progressbar while the markers is loading.
But the problem is that the progressbar is gone before the render.
I'm using the AsyncTask to render and I am adding the marker in the onProgressUpdate.
public class GetMarkersAsync extends AsyncTask<String, HistoricoTO, List<HistoricoTO>> {
private final static String OBTER = "http://10.0.0.65/Service.asmx/getEnvios";
GoogleMap map;
private Activity activity;
private ProgressBar progressBar;
public GetMarkersAsync (GoogleMap map, Activity activity) {
this.map = map;
this.activity = activity;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = (ProgressBar) activity.findViewById(R.id.progressBar1);
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected List<HistoricoTO> doInBackground(String... params) {
WebService ws = new WebService();
String response = ws.makeRequest(OBTER);
List<HistoricoTO> listaHistoricos = new ArrayList<HistoricoTO>();
try {
JSONArray array = new JSONArray(response);
HistoricoTO historico;
JSONObject jsonObject;
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
historico = new HistoricoTO();
historico.setName(jsonObject.getString("name"));
historico.setLatitude(jsonObject.getDouble("latitude"));
historico.setLongitude(jsonObject.getDouble("longitude"));
listaHistoricos.add(historico);
publishProgress(historico);
}
} catch (JSONException e) {
e.printStackTrace();
}
return listaHistoricos;
}
#Override
protected void onProgressUpdate(HistoricoTO... historicos) {
super.onProgressUpdate(historicos);
drawMarker(this.map, historicos[0]);
}
#Override
protected void onPostExecute(List<HistoricoTO> historicoTOs) {
super.onPostExecute(historicoTOs);
progressBar.setVisibility(View.GONE)
}
private void drawMarker(GoogleMap gmap, HistoricoTO historicoTO)
{
MyItem offsetItem = new MyItem(historicoTO.getLatitude(), historicoTO.getLongitude(), historicoTO);
MainActivity.mClusterManager.getMarkerCollection().addMarker(mo);
MainActivity.mClusterManager.addItem(offsetItem);
gmap.addMarker(mo);
}
}
PS: It's working, the ProgressBar is showing, but the problem is that the markers only shows when I "move" the map ou touch.

every time you add a new marker, invalidate map again.
so it will draw your item on map.
map.invalidate()

Related

How to automatically refresh a Listview? [duplicate]

This question already has answers here:
android auto-refresh listview items
(2 answers)
Closed 4 years ago.
I have an android listview, but I have to relance the application every time that I want to refresh the list. I have two questions, please:
1) How to refresh it automatically?
2) How to do to receive a notification when an item is added to the database?
So it just tests if an item is added, I receive a notification, when I Click on it I will be able to see the list of items.
This is my code:
public class MainActivity extends Activity {
ListView SubjectFullFormListView;
ProgressBar progressBar;
String HttpURL = "http://254.221.325.11/test/Subject.php";
ListAdapter adapter ;
List<Subject> SubjectFullFormList;
EditText editText ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
SubjectFullFormListView = (ListView) findViewById(R.id.SubjectFullFormListView);
editText = (EditText)findViewById(R.id.edittext1);
progressBar = (ProgressBar) findViewById(R.id.ProgressBar1);
new ParseJSonDataClass(this).execute();
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subject subject;
SubjectFullFormList = new ArrayList<Subject>();
for (int i = 0; i < jsonArray.length(); i++) {
subject = new Subject();
jsonObject = jsonArray.getJSONObject(i);
subject.Subject_Name = jsonObject.getString("SubjectName");
subject.Subject_Full_Form = jsonObject.getString("SubjectFullForm");
SubjectFullFormList.add(subject);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
SubjectFullFormListView.setVisibility(View.VISIBLE);
adapter = new ListAdapter(SubjectFullFormList, context);
SubjectFullFormListView.setAdapter(adapter);
}
}
}
I find a solution but I don't know how and where to insert it:
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new JSONParse().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
Thank you.
-> Write a runnable thread which calls the API of the list regularly after some time and on its response change the list in the adapter and call notifydatasetchanged().
-> By using FCM you can get the solution to question 2. When an item is added in DB generate a notification from server side and send it to clients sides and by using pending intent you can show the list when user tap on the notification.
(OR)
-> You can use the real-time DB Like Firebase DB or Realm etc. for this approach. This DB notify you when an item added to the list and you don't need threads to refresh list.

How to make ImageView from gallery bigger when clicked

I have a gallery in my app, with a GridLayout and I want that when the user clicks on it, it pops this effect , ¿How can I achieve that?
if anyone could tell me how the effect it is called or a library or something to how can I do that I would really appreciate it, so far I have tried this library with no luck https://github.com/mzelzoghbi/ZGallery?utm_source=android-arsenal.com&utm_medium=referral&utm_campaign=4987
Here is my code if anyone could see the error:
public class BusinessPremiumGallery extends AppCompatActivity implements GridClickListener
{
GalleryAdapter galleryAdapter;
Gson gson;
private static final Type BUSINESS_TYPE = new TypeToken<ArrayList<Business>>() {}.getType();
JsonObject images;
GridLayoutManager layoutManager;
ArrayList<Business> arrayGallery;
ArrayList<String> arrayImages;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_premium_gallery);
Bundle bundle = getIntent().getExtras();
final int values = bundle.getInt("no");
new PlifRequestBase(BusinessPremiumGallery.this) {
#Override
public JsonObject onHttpOk(JsonObject response) throws JSONException {
JsonObject respuesta, details, location, geolocation, matrix, schedules_array;
JsonArray data,branches, phones, schedules,extra_services,user_images;
respuesta = response;
int catalog_id;
String catalog_descrip,catalog_name,catalog_image,image;
Log.d("VALUES2",String.valueOf(values));
arrayGallery=new ArrayList<Business>();
gson=new Gson();
user_images= respuesta.get("user_images").getAsJsonArray();
if(user_images.size()<0){
arrayGallery=null;
images=null;
}else {
arrayGallery=gson.fromJson(user_images,BUSINESS_TYPE);
for (int i = 0; i < user_images.size(); i++) {
images = user_images.get(i).getAsJsonObject();
image=images.get("image").getAsString();
Log.d("IMAGES",image);
Log.d("CATALOG",String.valueOf(images));
}
}
if (BusinessPremiumGallery.this == null)
return response;
BusinessPremiumGallery.this.runOnUiThread(new Runnable() {
public void run() {
RecyclerView recycler = (RecyclerView) BusinessPremiumGallery.this.findViewById(R.id.recycler_gallery);
galleryAdapter = new GalleryAdapter(BusinessPremiumGallery.this, arrayGallery, R.layout.row_gallery_premium);
recycler.setNestedScrollingEnabled(false);
layoutManager = new GridLayoutManager(BusinessPremiumGallery.this, 2);
recycler.setLayoutManager(layoutManager);
recycler.setAdapter(galleryAdapter);
}
});
return respuesta;
}
#Override
public void onHttpCreate(JsonObject response) throws JSONException
{
}
}.execute("businesses/"+String.valueOf(values), "GET");
}
#Override
public void onBackPressed()
{
super.onBackPressed(); // optional depending on your needs
}
#Override
public void onClick(int i) {
ZGallery.with(this, arrayImages)
.show();
}
}

App crashes at setImageResource()

I am getting a NullPointerException at
image.setImageResource(R.drawable.cover);
Here's my code:
NewsFeed.this.runOnUiThread(new Runnable(){
#Override
public void run() {
//Your code to run in GUI thread here
image.setImageResource(R.drawable.cover);
}
});
This code is running in a doInBackground() method. This is my ImageView in XML:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
NewsFeed.java
public class NewsFeed extends ListActivity {
MainActivity mainAct = new MainActivity();
private ProgressDialog pDialog;
// json url
// json tags
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_ID = "id";
private static String TAG_MESSAGE = "message";
private static final String TAG_CREATETIME = "created_time";
protected static final String JSONObject = null;
// contacts JSONArray
JSONArray contacts = null;
TimerTask timerTask;
Handler handler;
Timer ourtimer;
String url, gotToken, static_token, imgUrl, nextUrl = "none",
prevUrl = "none", paging;
ImageView image;
Bitmap myBitmap;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Bundle gotBasket = getIntent().getExtras();
// gotToken = gotBasket.getString("Access_Token");
static_token = "xxxxxxxxxxxxxxxx";
url = "https://graph.facebook.com/v2.2/awaaziitkgp/feed?access_token="
+ static_token;
setContentView(R.layout.news_feed);
image = (ImageView) findViewById(R.id.imageView1);
final TextView button1 = (TextView) findViewById(R.id.button1);
final TextView newPosts = (TextView) findViewById(R.id.nextPosts);
final TextView prevPosts = (TextView) findViewById(R.id.previousPosts);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Calling async task to get json
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_DATA);
JSONObject pagingObj = jsonObj.getJSONObject("paging");
// String nextObj = pagingObj.getString("next");
nextUrl = pagingObj.getString("next");
// JSONObject prevObj= pagingObj.getJSONObject("previous");
prevUrl = pagingObj.getString("previous");
Log.d("contact.length", String.valueOf(contacts.length()));
// looping through All Contacts
for (int i = 0; i < 25; i++) {
JSONObject c = contacts.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();
String message = null;
String id = c.getString(TAG_ID);
data.put(TAG_ID, id);
if (c.has("description") == true) {
message = c.getString("description");
Log.d("Getting Description", message);
}
if (c.has("picture") == true) {
try {
Log.d("IT HAS PICTURE! TADA!!", "Image Found");
imgUrl = c.getString("picture");
Thread thread = new Thread(){
public void run(){
System.out.println("Thread Running");
NewsFeed.this.runOnUiThread(new Runnable(){
#Override
public void run() {
//Your code to run in GUI thread here
URL newUrl = null;
try {
newUrl = new URL(imgUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myBitmap = getBitmapFromUrl(newUrl);
image.setImageBitmap(myBitmap);
}
});
}
};
thread.start();
} catch (Exception e) {
Log.d("ERROR LOADING IMAGE",
"Why you do this, InputStream? Why?");
}
}else{
NewsFeed.this.runOnUiThread(new Runnable(){
#Override
public void run() {
//Your code to run in GUI thread here
((ImageView) findViewById(R.id.imageView1)).setImageResource(R.drawable.cover);
}
});
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
Here you can get a solution.
((ImageView)findViewById(R.id.image_view1)).setImageResource(R.drawable.cover);
XML Snippet:
<ImageView
android:id="#+id/image_view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
You are trying to inflate a layout then use a view from another layout..
since you used R.layout.activity_main you can only use the views inside that layout nothing more..
but in your case you used the image1 = (ImageView) findViewById(R.id.dice1); which will reference a null value because it reside in your MAIN.xml not in activity_main.
So what you need to do is instead of using the activity_main layout use the appropriate layout which is setContentView(R.layout.MAIN);

Where do I put the function to display the loading process?

I want to display a loading process when my application is loading data from the database.
This is my Java file.
Where do I have to put the function to display the loading process?
public class AksesServerActivity extends ListActivity {
private static String link_url = "http://plnskh.zz.mu/android/berita/cekdaftar.php";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, daftar_artikel,
R.layout.list_item,
new String[] { AR_JUDUL, AR_CONTENT, AR_ID}, new int[] {
R.id.judul, R.id.content, R.id.kode});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String kode = ((TextView) view.findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(AksesServerActivity.this, DetailAksesServer.class);
in.putExtra(AR_ID, kode);
startActivity(in);
}
});
}
}
public class LongOperation extends AsyncTask<String, String, String>
{
ProgressDialog pdialog;
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pdialog.dismiss();
this.adapter_listview();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(NewsActivity.this);
pdialog.setMessage("Loading");
pdialog.show();
}
}
for more clarification about asynchronous task and its methods, check here
You must use AsyncTask class, override doInBackground method to perform your databse fetch, onPreExecute method to show your loading and onPostExecute to hide it. you can refer AsynTask process and AsynTask post for more information

how to show data in url from input text using editext

i want make some process in my aplication to input some text first, after that, When user clicks the done button on the screen keyboard(using android:imeOptions="actionSearch") Isome data will show from this url :
("http://www.aaaa.com/selectAgent.htm?n="+cari_agen);
but when i make some process, there's nothing happen, my code still load all data, not specific as cari_agen, this is my source code :
public class MainActivity extends Activity {
GridView gridView;
private static final String ATASAN = "atasan";
private static final String KODE_AGEN = "kode_agen";
private static final String JENIS = "jenis";
private static final String NO_AAJI = "no_aaji";
private static final String NAMA_AGEN = "nama_agen";
List AgenList = new ArrayList();
boolean boolStatusKoneksi=true;
private ProgressDialog Dialog;
protected Context applicationContext;
EditText cari;
SearchView search;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
search=(SearchView) findViewById(R.id.searchView1);
cari=(EditText) findViewById(R.id.search);
cari.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
new AgenAsyncTask().execute();
return true;
}
return false;
}
});
}
public class AgenAsyncTask extends AsyncTask<String, String, String>
{
String cari_agen = cari.getText().toString();
#Override
protected void onPreExecute() {
super.onPreExecute();
Dialog = new ProgressDialog(MainActivity.this);
Dialog.setMessage("Mohon Tunggu sebentar...");
Dialog.setIndeterminate(false);
Dialog.setCancelable(true);
Dialog.show();
}
protected String doInBackground(String... args) {
String url =("http://www.aaaa.com/selectAgent.htm?n="+cari_agen);
try{
JSONParser j=new JSONParser();
JSONArray jsonArray = j.takeJson(url);
for(int i =0; i<jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
if (c.has("nama_agen"))
Log.v(NAMA_AGEN,"Nama agen=") ;
map.put("nama_agen", c.get("nama_agen").toString());
if (c.has("atasan"))
map.put("atasan", c.get("atasan").toString());
if (c.has("jenis"))
map.put("jenis", c.get("jenis").toString());
AgenList.add(map);
if (c.has("no_aaji"))
map.put("no_aaji", c.get("no_aaji").toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String arg)
{
Dialog.dismiss();
GridView gridview = (GridView) findViewById(R.id.gridview);
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, AgenList, R.layout.list_item,
new String[] { NAMA_AGEN, ATASAN, JENIS,NO_AAJI }, new int [] {R.id.nama_agen, R.id.atasan, R.id.jenis,R.id.no_aaji});
gridview.setAdapter(adapter); }
i hope somebody can help me to solve this problem, thank u

Categories

Resources