I have a Activity that contains over 100 complex views (with images, text views etc). Showing up these views is to hard to do it without a Thread that loads the views asynchronously. So I tried to do it with an AsyncTask. I am not sure whether this is the correct way because the "hard staff" is something that HAS to be done in the UI Thread.
Now I've got the problem that the UI freezes though I used the onProgressUpdate for adding the views in the to parent view. I thought that this would result in single loading views that appear successive in the parent view. But this is not the case.
doInBackground fires all publishProgress calls and after that the main thread is blocked (activity frozen, loadbar does not rotate anymore). Is there a way to achieve what I wanted to have? I looked for solutions but alway ended up with ideas of using AsyncTask and no one had to do view-stuff as "hard staff". I am not using "get" in the AsyncTask what seems to be a problem with AsyncTask.
Here is my code for this. If you need any further information please tell me!
Is there any other way to solute this problem? Is my AsyncTask implementation not correct? I am looking for a way to load these complex views asyncronous to the parent view without blocking the main thread.
Thanks in advance!
public class LoadKraut extends AsyncTask<Integer,Kraut,Void> {
private Context context;
private LinearLayout parent;
private HashMap<String,HeadlineAlphabet> headlinesAlphabet = new HashMap<String, HeadlineAlphabet>();
private long time;
private Integer kategorie;
private char letter = 'X';
private int counter = 0;
private ProgressDialog dialog;
public LoadKraut(Context context) {
/**
* Kategorie:
* 1 - A-Z
* 2 - Notiz
* 3 - Favorit
* 4 - Giftig
*/
Log.i("Kraut", "Start thread" + (System.currentTimeMillis()-time) + "ms");
this.context = context;
this.dialog = new ProgressDialog(context);
this.time = System.currentTimeMillis();
}
#Override
protected void onPreExecute() {
dialog.setMessage("Lade Kräuter. Dieser Vorgang kann einen Moment dauern.");
dialog.show();
}
#Override
protected Void doInBackground(Integer... params) {
this.kategorie = params[0];
//Create overview
try {
DatabaseHelper databaseHelper = new DatabaseHelper(context);
Dao<Kraut,Integer> dao = databaseHelper.getKrautDAO();
parent = (LinearLayout) ((Activity) context).findViewById(R.id.ll_conainter_sv_uebersicht_kraeuter);
//setKraeuter(list, linearLayout, giftig)
long test = System.currentTimeMillis();
List<Kraut> list = new ArrayList<>();
switch (kategorie) {
case 1:
list = dao.queryForAll();
break;
case 2:
list = dao.queryBuilder().where().ne("notiz","").query();
break;
case 3:
list = dao.queryBuilder().where().eq("favorit",true).query();
break;
case 4:
list = dao.queryBuilder().where().eq("toedlichBunny",true).query();
break;
}
Log.i("Kraut","Fetching duration: " + String.valueOf(System.currentTimeMillis() - test));
Iterator<Kraut> iterator = list.iterator();
while(iterator.hasNext()) {
Kraut kraut = iterator.next();
Log.i("Kraut","called pp for" + kraut.getName());
publishProgress(kraut);
}
} catch (SQLException e) {
e.printStackTrace();
}
Log.i("Kraut", "End " + (System.currentTimeMillis()-time) + "ms");
return null;
}
#Override
protected void onProgressUpdate(Kraut... value) {
//Set all Krauts and headlines A-Z
long test = System.currentTimeMillis();
Kraut kraut = value[0];
Log.i("Kraut", String.valueOf(counter));
if((kategorie==1 || kategorie==4) && kraut.getName().charAt(0)!=letter) {
letter = kraut.getName().charAt(0);
HeadlineAlphabet letterHeadline = new HeadlineAlphabet(context);
letterHeadline.setText(String.valueOf(kraut.getName().charAt(0)));
headlinesAlphabet.put(String.valueOf(letterHeadline.getText()),letterHeadline);
parent.addView(letterHeadline);
}
KrautView krautView=null;
if(kategorie==1 || kategorie==3) {
krautView = new KrautUebersicht(context,kategorie);
} else if(kategorie==2) {
krautView = new KrautUebersichtNotiz(context);
}
if(krautView!=null) {
krautView.setKraut(kraut);
parent.addView((LinearLayout) krautView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
parent.getRootView().invalidate();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
Log.i("Kraut","Kraut View creation duration: " + String.valueOf(System.currentTimeMillis() - test));
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(kategorie==1) {
//Set Alphabet Column right side
ArrayList<String> anfangsbuchstaben = Kraut.getAnfangsbuchstaben(context);
// Do this with an xml !
for (int i = 1; i <= 26; i++) {
//Log.i("Kraut", String.valueOf(i));
String currentLetter = Helper.getCharForNumber(i);
int id = context.getResources().getIdentifier("tv_"+currentLetter.toLowerCase(),"id",context.getPackageName());
TextView textView = (TextView) ((Activity) context).findViewById(id);
//If no Kraut contains Letter
if (!anfangsbuchstaben.contains(currentLetter)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(context.getResources().getColor(R.color.darkgrey, context.getTheme()));
} else {
textView.setTextColor(context.getResources().getColor(R.color.darkgrey));
}
//Make clickable to jump to A-Z Headlines
} else {
textView.setOnClickListener(new JumpToLetterOnClickListener(headlinesAlphabet));
}
}
}
parent.invalidate();
if(dialog.isShowing()) {
dialog.dismiss();
}
}
}
Note that onProgressView() is called repeatedly as your AsyncTask runs. Therefore, it should be kept as short as possible. This also means that your current code is creating lots of views and adding them to the UI. Instead, you should add the view just once and then update its data in onProgressView().
Also, as Mike M. states in the comments, you should not call Thread.sleep() in onProgressView() since it runs on the UI thread. This is most likely the main reason your app is freezing.
Related
One of my app's activities has ran into an issue; the problem seems to be an asynk-task, which get information from the server and generate a list of n elements in a view using that data, this, get the activity stuck in the white load screen instead of rendering the view.
No crashes or errors.
I can press back button and return to previous activity(Not freeze).
Android monitor show no cpu usage.
Here is the code.Is called at the end of onCreate()
new AsyncTask() {
#Override
protected void onPreExecute() {
mProgressDialog.show();
}
#Override
protected Object doInBackground(Object[] params) {
Document dom = null;
Detalle detalle= getIntent().getParcelableExtra("pedido");
try {
dom=DetalleToXml.getDom(detalle);
} catch (Exception e) {
e.printStackTrace();
}
return dom;
}
protected void onPostExecute(Object o) {
Document dom = (Document)o;
mProgressDialog.dismiss();
TableLayout t = (TableLayout) contentView.findViewById(R.id.grid_layout_pedido);
t.removeAllViewsInLayout();
final NodeList rows = dom.getElementsByTagName("row");
if(rows.getLength() == 0) {
Toast.makeText(DetallesPedido.this, "La búsqueda no ha tenido resultados.", Toast.LENGTH_SHORT).show();
}else{
for(int i = 0; i < rows.getLength(); i++){
Element e = (Element)rows.item(i);
LayoutInflater inflater = LayoutInflater.from(getBaseContext());
String rowid = UtilesDom.getValue(e, "rowid");
String articulo = UtilesDom.getValue(e, "articulo");
String precio_venta = UtilesDom.getValue(e, "precio_venta");
String cantidad = UtilesDom.getValue(e, "cantidad");
String descripcion = UtilesDom.getValue(e, "descripcion");
LinearLayout bigRow=(LinearLayout)inflater.inflate(R.layout.pedido_detalle,null);
TextView tv=(TextView) bigRow.findViewById(R.id.detalle_row_textView1);
tv.setText(articulo);
tv=(TextView) bigRow.findViewById(R.id.detalle_row_textView3);
tv.setText(precio_venta);
tv=(TextView) bigRow.findViewById(R.id.detalle_row_textView2);
tv.setText(cantidad);
tv=(TextView) bigRow.findViewById(R.id.detalle_row_textView4);
tv.setText(descripcion);
try {
bigRow.setId(Integer.parseInt(rowid));
} catch (Exception e2) {
e2.printStackTrace();
}
bigRow.setTag(articulo);
bigRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String codigo = (String) v.getTag();
final Context context = v.getContext();
final int rowid = v.getId();
Intent intent = new Intent(context, DetalleFicha.class);
Bundle b = new Bundle(3);
b.putInt("rowid", rowid);
b.putInt("operation",UtilesABM.UPDATE);
b.putString("caller","DetallesPedido");
intent.putExtras(b);
intent.putExtra("pedido",getIntent().getParcelableExtra("pedido"));
loaded = false;
startActivity(intent);
}
}
);
//UtilesViews.setDefaultPadding(tv);
t.addView(bigRow);
}
}
super.onPostExecute(o);
}
}.execute(query);
By debugging i can reach the Loop.java class right after execute() and there is where gets stuck.
Any ideas of how to fix it or the cause of the problem?
You are performing very performance costly call
LinearLayout bigRow=(LinearLayout)inflater.inflate(R.layout.pedido_detalle,null);
which can take too much time, and since you are doing it in onPostExecute call, which is being called on main thread, so main thread will gets blocked if number of rows are huge and app becomes unresponsive
Solution to this is, you can use recycler view
My app normally works just fine, until I face a strange problem on specific device. There are 2 activities in App. After I start ActivityB inside of ActivityA, ActivityA starts with no issue. However, after I go back to the ActivityA with pushing back hardware button or calling finish(); inside of closeButton in ActivityB, ActivityA reloads itself. It triggers onCreate() again and reloads all its contents. And I'm not changing orientation of phone. This strange behavior only appears in 15 phones over 1.000 download of app.
This problem only occurs on Galaxy S3 Android OS 4.1.2. And this is also strange.
Do you have any idea why this is happening?
When I start a new Activity inside of button listener like this:
ActivityA.java (MesajlarListViewActivity)
public class MesajlarListViewActivity extends TrackedActivity {
Context context = null;
// contacts JSONArray
JSONArray contacts = null;
ArrayList<Message> productArray = new ArrayList<Message>();
private ProductAdapter adapter;
private ListView productList;
private Runnable viewOrders;
private HoloProgressIndicator profilInfoProgress = null;
ImageView kapatButton = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mesajlar_list);
context = this;
kapatButton = (ImageView) findViewById(R.id.kapat_button);
/* kapat button onclick listener. */
// =================================================================================================================
kapatButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
// Set vibration on touch.
KnetGenericClass.vibratePhone(context);
finish();
}
});
// =================================================================================================================
//Progress bar.
profilInfoProgress = (HoloProgressIndicator) findViewById(R.id.profil_info_progress);
// cheking internet connectivity.
if(KnetGenericClass.checkInternetConnection(context))
{
// start task!
/* internet var ise web service baglantisi kurmaya baslayabiliriz. */
startActivityIndicatorWithThread();
}
else
{
KnetGenericClass.printErrorMessage(context, "Bağlantı Hatası",
"Lütfen internet bağlantınızı kontrol ediniz.");
}
productList = (ListView) findViewById(R.id.product_list);
adapter = new ProductAdapter(this, R.layout.message_row, productArray);
productList.setAdapter(adapter);
// When user click a view on list view new page is appearing.
productList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// Set vibration on touch.
KnetGenericClass.vibratePhone(context);
/* Navigate to message detay activity class with ilan ID. */
Intent myIntent = new Intent(view.getContext(), MesajDetayActivity.class);
myIntent.putExtra("messageID", productArray.get(position).getId());
startActivity(myIntent);
// setting image of clicked message null.
RelativeLayout relativeLayout = (RelativeLayout) view;
ImageView unreadedImageView = (ImageView) relativeLayout.findViewById(R.id.unreaded_image);
unreadedImageView.setImageResource(0);
}
});
}
public class ProductAdapter extends ArrayAdapter<Message> {
ArrayList<Message> items;
public ProductAdapter(Context context, int textViewResourceId, ArrayList<Message> objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.message_row, null);
}
ImageView unreadedImageView = (ImageView) convertView.findViewById(R.id.unreaded_image);
TextView productName = (TextView) convertView.findViewById(R.id.product_name);
TextView productDetail = (TextView) convertView.findViewById(R.id.product_detail);
// TextView productDate = (TextView)
// convertView.findViewById(R.id.product_date);
TextView sentDate = (TextView) convertView.findViewById(R.id.product_date);
productName.setText(items.get(position).getSender());
productDetail.setText(items.get(position).getTitle());
// String bodyNoHTML = items.get(position).getBody();
if(items.get(position).getIsReaded())
{
unreadedImageView.setImageResource(0);
}
else
{
unreadedImageView.setImageResource(R.drawable.bluedot);
}
String dateStr = items.get(position).getSentDate();
try
{
sentDate.setText(dateStr.substring(6, 8) + "." + dateStr.substring(4, 6) + "." + dateStr.substring(0, 4)
+" "+dateStr.substring(8, 10)+":"+dateStr.substring(10, 12));
}
catch(Exception e)
{
sentDate.setText("");
}
return convertView;
}
}// #end of product adapter class.
/* web service'e baglanti kurulan methodu threadin icerisinde cagiriyoruz. */
public void startActivityIndicatorWithThread()
{
// ==============================================================================================
// getting ilan details into arraylist.
// setting up thread.
viewOrders = new Runnable() {
public void run()
{
getMessageListFromWebService();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
profilInfoProgress.start();
// ==============================================================================================
// #end of the thread declaration.
}
public void getMessageListFromWebService()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser(context);
// getting JSON string from URL
JSONArray jsonArray = jParser.getAuthorizedInfoFromUrlToJSONArray(
WebServiceInfo.getKnetWebServiceLink()+"/API/Member/GetInboxMessageList", MainActivity.getAccessToken());
// if json is null then there is a problem.
if(jsonArray == null)
{
// if json array is null then print error message.
runOnUiThread(showAlertMessage);
runOnUiThread(returnRes);
return;
}
try
{
// Eger aranilan kritere gore ilan yok ise hata mesaji basiyoruz.
if(jsonArray.length() == 0)
{
// if json array is null then print error message.
runOnUiThread(showAlertIlanYokMessage);
runOnUiThread(returnRes);
return;
}
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
// String id = c.getString(TAG_ID);
String id = c.getString("Id");
String sender = c.getString("Sender");
// String body = c.getString("Body");
String title = c.getString("Title");
String sentDate = c.getString("SentDate");
Boolean isReaded = c.getBoolean("IsRead");
Message productObject = new Message(id, sender, "", title, sentDate, isReaded);
productArray.add(productObject);
}
}
catch (Exception e)
{
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
// #end of thread.
private Runnable returnRes = new Runnable() {
public void run()
{
profilInfoProgress.stop();
adapter.notifyDataSetChanged();// refreshing data over adapter in
// list view.
}
};
// #end of thread.
private Runnable showAlertMessage = new Runnable() {
public void run()
{
// Bu hata genelde linkteki problemden, servera ulasilamamasindan
// veya timeouttan meydana gelir.
Toast.makeText(getApplicationContext(),
"Mesajlar alınamadı lütfen daha sonra tekrar deneyiniz.",
Toast.LENGTH_LONG).show();
}
};
private Runnable showAlertIlanYokMessage = new Runnable() {
public void run()
{
// Bu hata aranilan kelimeye gore ilan bulunamazsa gelir.
Toast.makeText(getApplicationContext(),
"Mesajlar bulunamadı.",
Toast.LENGTH_LONG).show();
}
};
}
========================================================================
ActivityB.java (MesajDetayActivity.java)
public class MesajDetayActivity extends TrackedActivity {
private HoloProgressIndicator profilInfoProgress = null;
TextView titleTextView = null;
TextView senderTextView = null;
TextView dateTextView = null;
WebView bodyWebView = null;
Message messageObject = null;
String messageID = null;
ImageView kapatButton = null;
Context context;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mesajdetaylari);
context = this;
kapatButton = (ImageView) findViewById(R.id.kapat_button);
/* kapat button onclick listener. */
// =================================================================================================================
kapatButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
// Set vibration on touch.
KnetGenericClass.vibratePhone(context);
finish();
}
});
// =================================================================================================================
//Progress bar.
profilInfoProgress = (HoloProgressIndicator) findViewById(R.id.profil_info_progress);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
messageID = extras.getString("messageID");
}
titleTextView = (TextView) findViewById(R.id.title_textview);
senderTextView = (TextView) findViewById(R.id.sender_textview);
dateTextView = (TextView) findViewById(R.id.date_textview);
bodyWebView = (WebView) findViewById(R.id.mesaj_webView);
// Show the ProgressDialog on this thread
profilInfoProgress.start();
// Start a new thread that will download all the data
new MakeItTask().execute();
}
// Async task.
private class MakeItTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... args)
{
Log.i("MyApp", "Background thread starting");
// This is where you would do all the work of downloading your data
// getting message detay
/* connect to web service */
getMessageDetayFromWebService();
return null;
}
protected void onPostExecute(Object result)
{
// Pass the result data back to the main activity
// TakipListeActivity.this.data = result;
try
{
titleTextView.setText("Başlık: " + messageObject.getTitle());
senderTextView.setText("Gönderen: " + messageObject.getSender());
dateTextView.setText("Tarih: " + messageObject.getSentDate().substring(6, 8) + "."
+ messageObject.getSentDate().substring(4, 6) + "."
+ messageObject.getSentDate().substring(0, 4));
if(!messageObject.getBody().contains("img"))
{
bodyWebView.loadDataWithBaseURL(null, messageObject.getBody(), "text/html", "UTF-8", null);
}
}
catch (Exception e)
{
Log.e(CONNECTIVITY_SERVICE, "Mesaj Detayi bilgileri basilamadi.");
}
profilInfoProgress.stop();
}
}
/* web service'e baglanti kurulan methodu threadin icerisinde cagiriyoruz. */
public void getMessageDetayFromWebService()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser(context);
// getting JSON string from URL
JSONObject jsonObject = jParser.getAuthorizedInfoFromUrlToJSONObject(
WebServiceInfo.getKnetWebServiceLink()+"/API/Member/GetInboxMessage/" + messageID, MainActivity.getAccessToken());
// if json is null then there is a problem.
if(jsonObject == null)
{
return;
}
try
{
String title = jsonObject.getString("Title");
String id = jsonObject.getString("Id");
String sender = jsonObject.getString("Sender");
String date = jsonObject.getString("SentDate");
String body = jsonObject.getString("Body");
messageObject = new Message(id, sender, body, title, date, true);
}
catch (Exception e)
{
Log.e("BACKGROUND_PROC", e.getMessage());
}
}// #end of getIlanDetayFromWebService.
}
Edit: Not only these two activities have this problem, all the activities acting same behavior on some phones.
Check to see whether Don't keep activities under Settings > System > Developer options > Apps is enabled or not.
The Activity documentation (http://developer.android.com/reference/android/app/Activity.html) says the following about the lifecycle of a background activity:
A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left it.
In other words, ActivityA may or may not be destroyed by the operating system while ActivityB is active, so this situation has to be handled in the code. If ActivityA has been destroyed, onCreate(Bundle) will be called, when the user presses the back button in ActivityB.
There's an Android developer setting called "Do not keep activities". The description for this option is "Destroy every activity as soon as the user leaves it." This sounds like a good description of what you're seeing, and since you're only seeing it on a few phones the idea that this is caused by a non-default system setting seems plausible.
Ideally your app would still work in this scenario, even if less optimally. But if this setting is a problem for your app, you may wish to document this problem for your users.
Have you tried changing the launchmode in the Android Manifest? Try adding this to your Activity declaration:
android:launchMode="singleTask"
Next, try using startActivityForResult, instead of startActivity. This will force Activity A to call its onActivityResult(int, int, Intent) method when Activity B finishes - which may skip this (buggy) call to onCreate. Then, in Activity A, implement the method to do something (such as printing a debug statement):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.i("Test", "Did this work???");
//TODO send notification to your server to verify this works?
}
I do not see any problem in this behaviour.
In case you wish to preserve the state of ActivityA, make use of the methods onSaveInstanceState and onRestoreInstanceState. See Activity Lifecycle at http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle for more details.
See also https://stackoverflow.com/a/10492967/332210 for a deeper understanding.
You can try one thing provide your layout in onCreate() and do the rest of the work in onStart() ?? if it works??
LIKE:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
}
and
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.i(TAG, "On Start .....");
}
See Activity Lifecycle
Perhaps you should use
Intent startIntent = new Intent(view.getContext(), ActivityB.class);
startActivity(startIntent);
finish() ;
And
Intent startIntent = new Intent(view.getContext(), ActivityA.class);
startActivity(startIntent);
finish() ;
each time you go back or forward.
It too faced the exact problem and solved issue by Using android:launchMode="standard" in activity of manifest.
Override onStart() and onResume method in Activity A and check if the problem is still persist. and if possible please give your activtiy A and B code here.
Activity A uses layout R.layout.mesajlar_list
Activity B uses layout R.layout.mesajdetaylari
But both have the following line of code:
kapatButton = (ImageView) findViewById(R.id.kapat_button);
Which layout is R.id.kapat_button in? Using the same id in different layouts is a very risky thing to do. I can't guarantee it's causing what you're seeing, but it is the sort of thing that may cause weird behaviour.
I think it is not because of memory the limit.
https://www.box.com/s/7pd0as03bb8wwumuc9l9
You should test these two activities and check whether it is happening in this example too or not. Please share your AndroidManifest.xml file content too, it will help with debugging.
I got this issue recently, and this make me annoyed. I think that issue around 2 options solution to check but useless.
About the setting "Don't keep activities" corrected here, I used this code to check that it optional checked or not (my test device customize base on version 2.3.5 and not show this option):
private boolean isAlwaysFinishActivitiesOptionEnabled() {
int alwaysFinishActivitiesInt = 0;
if (Build.VERSION.SDK_INT >= 17) {
alwaysFinishActivitiesInt = Settings.System.getInt(getApplicationContext().getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0);
} else {
alwaysFinishActivitiesInt = Settings.System.getInt(getApplicationContext().getContentResolver(), Settings.System.ALWAYS_FINISH_ACTIVITIES, 0);
}
if (alwaysFinishActivitiesInt == 1) {
return true;
} else {
return false;
}
}
Result check is false in my case. I also check the memory when running application and it nothing occur.
you can use android:launchMode="singleTop"in manifest.
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
I have posted a question
Progress Dialog is not displaying while getting data from separate thread class
but I haven't got the appropriate answers. I have already used async task to display progress dialog but it is not displaying.
here is the sample code
public class JsonData extends AsyncTask<String, String, String> {
private ProgressDialog mProgressDialog;
Context context;
public JsonData(Context context)
{
this.context=context;
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setMessage("Loading Please Wait.");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected String doInBackground(String... aurl) {
String results="";
try {
int k=0;
URL url1;
url1 = new URL(aurl[0]);
InputStream input=url1.openStream();
BufferedInputStream bis=new BufferedInputStream(input);
ByteArrayBuffer baf=new ByteArrayBuffer(1000);
while((k=bis.read())!=-1)
{
baf.append((byte)k);
}
results=new String(baf.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return results;
}
#Override
protected void onPostExecute(String jsondata) {
mProgressDialog.dismiss();
}
}
Here is the method in which I have called the async task
private void getRecordsByCount(final String data) {
try {
int color=Color.BLACK;
tableLayoutGrid.removeAllViews();
final String[] details = data.split("_");
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(new Date());
String url = ipaddress + "/GrantLeavesList?Companyid=" + user_info.get("CompanyId") + "&divisionid=" + details[3] + "&userid=" + user_info.get("userid") + "&roleid="
+ user_info.get("RoleId") + "&Employeeid=" + user_info.get("EmployeeId") + "&leavetypeid=" + staticDetails.get(details[0]) + "&strStatus=" + staticDetails.get(details[1])
+ "&type=" + staticDetails.get(details[2]) + "&Date=" + formattedDate;
String url2=ipaddress + "/GrantLeavesChildList?Companyid=" + user_info.get("CompanyId") + "&divisionid=" + details[3] + "&userid=" + user_info.get("userid") + "&roleid="
+ user_info.get("RoleId") + "&Employeeid=" + user_info.get("EmployeeId") + "&leavetypeid=" + staticDetails.get(details[0]) + "&strStatus=" + staticDetails.get(details[1])
+ "&type=" + staticDetails.get(details[2]) + "&Date=" + formattedDate;
JsonData jdata=new JsonData(context);
jdata.execute(url,null,null);
String jsonString=jdata.get();
JSONObject obj=new JSONObject(jsonString);
JsonData jdataChild=new JsonData(context);
jdataChild.execute(url2,null,null);
String jsonChildString=jdataChild.get();
JSONObject objchild=new JSONObject(jsonChildString);
btnGrantSubmit.setVisibility(View.GONE);
if (obj != null) {
leaveforwardcounts = obj.getJSONArray("Table1");
leaveforwardchildcounts=objchild.getJSONArray("Table11");
ScrollView scrollGrid = new ScrollView(this);
TableRow datarow = new TableRow(this);
datarow.setWeightSum(100);
TableLayout table = new TableLayout(this);
for (int i = 0; i < leaveforwardcounts.length(); i++) {
btnGrantSubmit.setVisibility(View.VISIBLE);
JSONObject record = leaveforwardcounts.getJSONObject(i);
String applicantname = record.getString("Applicant");
String toDate = record.getString("ToDate");
String noofdays = record.getString("NumberOfDays");
String LOP = record.getString("LOP");
if(LOP!=null && LOP.trim().length()!=0)
{
color=Color.RED;
}
final int id = i;
final Button gridbutton = new Button(this);
gridbutton.setText(status);
gridbutton.setTextColor(Color.BLACK);
gridbutton.setBackgroundResource(R.drawable.grdbutton_30x30);
gridbutton.setGravity(Gravity.CENTER);
gridbutton.setPadding(2, 0, 2, 0);
gridbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeRadioButtonState(gridbutton, id, data);
}
});
gridbutton.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
setSelection(gridbutton);
return true;
}
});
TextView tvApplicantName = new TextView(this);
TextView tvToDate = new TextView(this);
TextView tvNoOfDays = new TextView(this);
TextView empty = new TextView(this);
TextView empty2 = new TextView(this);
if (applicantname.trim().length() >= 18) {
applicantname = applicantname.substring(0, 18);
}
tvApplicantName.setText(applicantname);
tvApplicantName.setTypeface(font2);
tvApplicantName.setWidth(70);
tvApplicantName.setTextColor(color);
tvApplicantName.setPadding(5, 0, 0, 0);
tvToDate.setText(toDate);
tvToDate.setTypeface(font2);
tvNoOfDays.setText(noofdays);
tvNoOfDays.setTypeface(font2);
tvNoOfDays.setGravity(Gravity.RIGHT);
Button ivDetails = new Button(this);
ivDetails.setText(" ");
ivDetails.setPadding(2, 0, 2, 0);
ivDetails.setBackgroundResource(R.drawable.detailsbutton_30x30);
ivDetails.setGravity(Gravity.CENTER);
ivDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
leaveDetails = new PopupWindow(showLeaveDetails(id, leaveforwardcounts,data,leaveforwardchildcounts), (int) (width * 0.8), height / 2, true);
leaveDetails.showAtLocation(mainlayout, Gravity.CENTER, 0, 0);
}
});
TableRow row = new TableRow(this);
row.setPadding(0, 3, 0, 3);
row.setWeightSum(100);
row.addView(tvApplicantName, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 55));
row.addView(tvNoOfDays, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 5));
row.addView(empty2, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20));
row.addView(ivDetails, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 5));
row.addView(empty, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 5));
row.addView(gridbutton, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 5));
table.addView(row);
}
scrollGrid.addView(table);
datarow.addView(scrollGrid, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 100));
tableLayoutGrid.addView(datarow);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I need to build page based on the data from Service. in my app there are about 20-30 services.. if i use async task as inner class it works well and good ...but How can reuse my code...
you dont need to start a background method for postExecute. as #baske wrote, you have problem with .get() - that is blocking your thread even if your are using AsyncTask.
try someting related to the linked question, so only add your YourActivityClass as a param to the construdtor of JsonData
public JsonData(YourActivityClass activity)
{
this.activity=activity;
mProgressDialog = new ProgressDialog(activity);
}
protected void onPostExecute(String jsondata) {
if (mProgressDialog != null || mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
if(jsondata!=null) {
activity.yourcallback(jsondata)
}
}
And define the yourcallback() in YourActivityClass
private void yourcallback(String data) {
jsonRecordsData=data;
showRecordsFromJson();
}
user, I think you need to understand better what the reasons are for using an AsyncTask and what the uses are of the callback/hook methods it provides.
Starting with the reason: if you have a long-running task, you cannot run this on the main thread (also called UI thread) because your app will eventually show ANR errors. Now if your long-running task would not need to show output on the screen (when it is done, progress reports, etc) you can very well put it in a worker thread and let it run by itself (possibly even delegating it to a Service to guarantee run-to-completion, but that is another story). However, a lot of times this isn't the case and you want to update your UI based on the outcome/progress of your long-running task. To do this you would have to somehow branch off a thread and do the work there, but, since you can only manipulate the UI from the main thread, you would have to post back the result on the main thread when you are done.
This is where we move to the AsyncTask and its hook methods. An AsyncTask is actually just a Utility class that helps you do exactly what is explained above: put your work on a separate thread and get a callback on your main thread when it is done (and the result is available). Checking the documentation you will find:
onPreExecute(): guaranteed to run on the main thread. Allows you to do stuff (like show a progress dialog) BEFORE the work starts.
doInBackground(): guaranteed to run on a background thread. Do you long running stuff here.
onPostExecute(): guaranteed to run on the main thread AFTER your doInBackground() has finished. The result of your task is now available and you can do stuff with it (like put it on the screen).
Getting back to your suggestions about your .get() method having a problem: since you are calling .execute() on your AsyncTask and .get()-ing the result immediately thereafter, chances are that the background job has not yet finished. Instead you should be doing whatever you wanted to do, starting at the .get() in the AsyncTask's onPostExecute. So if your task downloads an image and you want to show a "downloading" message to the user while it is running, you should do the following:
//pseudo code
void exampleButtonClicked() {
new AsyncImageDownloader.execute();
}
class AsyncImageDownloader extends AsyncTask {
onPreExecute() {
show "downloading";
}
doInBackground() {
downloadImg();
}
onPostExecute() {
hide "downloading";
put downloaded img on ImageView;
}
}
//end of pseudo code
Hope this helps.. Not going to code out your answer, because then you would have learned nothing ;-)
Cheers!
You can do UI operations only from an UI thread. Try running it on an UI thread.
runOnUiThread(new Runnable() {
public void run() {
mProgressDialog.show();
}
});
You can do on override methods onPreExecute() and implement for this code,
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog mProgressDialog = ProgressDialog.show(ActivityName.this, "Wait", "Loading....");
}
and onPostExecute() method implement and dismiss the dialog,
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (mProgressDialog != null || mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
Try the following:
#Override
protected void onPreExecute()
{
mProgressDialog =ProgressDialog.show(GmailInbox.this, "", "Please Wait",true,false);
super.onPreExecute();
}
I am very new to android. I got two activities A, B . Activity A parse the data from the sever and iterate through the levels. and calls the activity B through intent. Activity B takes some time to display the data so I am trying to display the progress bar. Here is my code.
public class Display extends Activity {
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.attributequestions);
new asynctask().execute();
}
class asynctask extends AsyncTask<Context,Void,Void>{
Survey[] surveyque=null;
// i hace created seperated class forsurvey that has info about data
String list[];
private ProgressDialog Dialog;
#Override
protected void onPreExecute()
{
Dialog=ProgressDialog.show(Display.this, "Parsing Data", "Please wait..........");
}
#Override
protected void onPostExecute(Void unused)
{
try
{
if(Dialog.isShowing())
{
Dialog.dismiss();
}
Intent intent=getIntent();
}
catch(Exception e)
{
Log.d("Onsitev4", "error");
}
}
#Override
protected Void doInBackground(Context... params) {
try {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.linearLayout1);
//getting exception here. I dont understant why
// I have declared layout params and displaying activities in another class
ButtonView c = new ButtonView();
c.layout=layout1;
c.context =getBaseContext();
DbCoreSqlSurveys surveys=new DbCoreSqlSurveys(getBaseContext());
Document doc =surveys.getSurveySet();
surveyquestions= GetSurveyLevels(doc,c );
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
}
return null;
}
}
public SurveyObject[] GetSurveyLevels(Document doc, ButtonView c) {
NodeList nlQuestions = doc.getElementsByTagName("Survey");
SurveyObject[] allsurveys = new SurveyObject[nlQuestions.getLength()];
for (int i = 0; i < nlQuestions.getLength(); i++){
Node survey = nlQuestions.item(i);
String f =survey.getNodeName();
Log.d("OnsiteV4", "survey " + f);
NodeList surveyChildNodes = survey.getChildNodes();
SurveyObject s=new SurveyObject();
for (int j = 0; j < surveyChildNodes.getLength(); j++){
Node surveyChild = surveyChildNodes.item(j);
String h =surveyChild.getNodeName();
Log.d("OnsiteV4", "survey child node = " + h);
if (h !="#text"){
Surveys t = Surveys.valueOf(h);
switch(t){
case KeySurvey:
s.KeySurvey=surveyChild.getTextContent();
displaySurveyLink(s.SurveyDescription,"",c,0,s.SurveyDescription,"","","","");
break;
case SurveyDescription:
s.SurveyDescription=surveyChild.getTextContent();
displaySurveyLink(s.SurveyDescription,"",c,0,s.SurveyDescription,"","","","");
break;
case SurveyUserCode:
s.SurveyUserCode=surveyChild.getTextContent();
break;
case Level1:
if(surveyChild.hasChildNodes()){
s.Level1= processLevel1Nodes(surveyChild,c,s.SurveyDescription);
}
break;
default:
break;
}
}
allsurveys[i]=s;
}
}
return allsurveys;
}
// methods iterating through levels that is not showed
private void displaySurveyLink(final String description, String tag, ButtonView c, int indentation, final String surveyDescription, final String level1description, final String level2description, final String level3description, final String level4description)
{
if (description == null || tag == null){
return;
}
final TextView tv = c.addButton(description,tag,indentation);
tv.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
final Intent intent = new Intent();
intent.setClass(v.getContext(),ActivityB.class);
intent.putExtra("KeyLevel",tv.getTag().toString());
intent.putExtra("SurveyDescription",surveyDescription);
intent.putExtra("level1description",level1description);
intent.putExtra("level2description",level2description);
intent.putExtra("level3description",level3description);
intent.putExtra("level4description",level4description);
intent.putExtra("Description",description);
if (tv.getTag() != null){
if (tv.getTag().toString() != ""){
startActivity(intent);
}
}
}
});
}
}
I am getting exception in doinbackground. I am confused . please help me..
You are getting an exception because you are accessing UI elements on a non-UI thread. The main thread that the application creates is the UI thread, and that's where all of your visual elements are created and therefore the only thread in which you should access them.
To appropriately use AsyncTask, you run your long-running operations in doInBackground, and you use onPreExecute, onPostExecute and onProgressUpdated to work with the UI (show/hide progress dialogs, update views, etc). Whenever I use an AsyncTask and I want to show progress, I override onProgressUpdated giving it parameter type Integer and I call publishProgress from doInBackground. This would require a change of the base class signature from AsyncTask<Context,Void,Void> to AsyncTask<Context,Integer,Void>. You can use other object types for this as well...I just use Integer as an example if you want to show the percentage of the task that is complete, for example.
It's becoz your code should throwing exception as you are doing UI stuff in the doinbackgound of asyc task. Please remove all the UI related work from doingbackgound method.
I am doing lazy loading and almost done with it. But would like to implement a progress dialog with it because it takes about 10seconds between starting the activity and finishing displaying the contents. Once I click on a button to start, it stays at the current page(Main.java) for about 4 second before moving to the next page(Activity.java). Then it takes about 2-4 seconds to display contents.
Tried the examples available here and on the net but they aren't working well (able to display the dialog but unable to do a proper dismiss after content are all downloaded).
Question is, how can I implement a progress indicator immediately once the user clicks on the button?
Activity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mStrings, dStrings );
list.setAdapter(adapter);
}
private String[] mStrings = {};
private String[] dStrings = {};
public Activity()
{
String imageC = "";
String textC = "";
try {
// Get the URL from text box and make the URL object
URL url = new URL(targetURL);
// Make the connection
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = reader.readLine();
Pattern sChar = Pattern.compile("&.*?;");
Matcher msChar = sChar.matcher(line);
while (msChar.find()) line = msChar.replaceAll("");
while (line != null) {
if(line.contains("../../"))
{
int startIndex = line.indexOf("../../") + 6;
int endIndex = line.indexOf(">", startIndex + 1);
String abc = "http://www.petschannel.com/";
String imageSrc = line.substring(startIndex,endIndex);
//complete full url
String xyz = abc +imageSrc;
xyz = xyz.substring(0,xyz.indexOf('"'));
xyz = xyz +";";
imageC += xyz;
mStrings = imageC.split(";");
line = reader.readLine();
}
if(line.contains("../../") == false)
{
line = reader.readLine();
}
if (line.contains("Gnametag"))
{
int startIndex = line.indexOf("Gnametag") + 10;
int endIndex = line.indexOf("<", startIndex + 1);
String gname = line.substring(startIndex,endIndex);
textC += "Name: "+gname+ "\n";
}
if (line.contains("Last Update"))
{
reader.close();
}
}
// Close the reader
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Firstly, you are doing your network call on the main thread, this is a classic no-no for performance reasons, amongst others. Never do any operation that may be time consuming on the main (ui) thread.
I would suggest using AsyncTask, which ensures in this case, that your network call would be done in a worker thread, and the result posted back to the main thread.
AsyncTask has methods to manage progress bars, onProgressUpdate and publishProgress that will help you solve your stated problem. There are many good articles about this, here is one.
Something like this:
final ProgressDialog myDialog = ProgressDialog.show(this, "Title", "Message");
Thread thread = new Thread(new Runnable() {
public void run() {
/* Your code goes here */
mHandler.sendEmptyMessage(0);
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
myDialog.dismiss();
}
}
}
thread.start();