How to read Alert Dialog in separate thread in android? - android

I have an AlertDialog builder in class. I am setting some message into it which comes from reading a file. Earlier as file text wasn't too large it use to load easily, now since the text has grown more it takes a time to load dialog and blocks UI. How can i run this in thread ?
Edited code :
public class Eula TaskCompleteListner{ {
static interface OnEulaAgreedTo {
void onEulaAgreedTo();
}
public static boolean show(final Activity activity,final Context context,final Boolean flag) {
final Preferences prefs = Preferences.getInstance();
Log.d(TAG, "insideEula");
if (!prefs.getEulaStatus(context)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
activity);
Log.d(TAG, "insideEulaLaunch");
builder.setTitle(R.string.eula_title);
builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.setEulaStatus(context, true);
if (activity instanceof OnEulaAgreedTo) {
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}
}
});
builder.setNegativeButton(R.string.eula_refuse,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
refuse(activity);
}
});
MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
public boolean onComplete(String result) {
builder.setMessage(data);
builder.create().show();
return false;
}
}) ;
MyAsync async= new MyAsync(this, activity) ;
async.excecute();
//builder.setMessage(readEula(activity)); //READING FILE AND SETTING HERE
//builder.create().show();
return false;
}
return true;
}
private static void refuse(Activity activity) {
activity.finish();
}
#Override
public boolean onComplete(String result) {
// TODO Auto-generated method stub
builder.setMessage(readEula(activity)); //READING FILE AND SETTING HERE
builder.create().show();
return false;
}
Async Task Class
public class MyAsync extends AsyncTask<Void, Void, String>{
public static final String ASSET_EULA = "EULA";
TaskCompleteListner taskCompleteListner;
Activity activity;
public interface TaskCompleteListner{
public boolean onComplete(String result);
}
public MyAsync(TaskCompleteListner taskCompleteListner,Activity activity) {
this.taskCompleteListner = taskCompleteListner;
this.activity=activity;
}
#Override
protected String doInBackground(Void... params) {
String data=(String)readEula(activity);
return data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
taskCompleteListner.onComplete(result);
}
private static CharSequence readEula(Activity activity) { //READING FILE HERE
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
buffer.append(line).append('\n');
byte[] latin1 = buffer.toString().getBytes("ISO-8859-1");
return new String(latin1);
//return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
}

You can use AsyncTask class, where you read your data in doInBackground() return the CharSequence and do the dialog.show() in onPostExecute().
EDIT:
heres what you can do,
create a class
private static class MyAsyncClass extends AsyncTask<Void,Void,CharSequence > {
Activity activity;
ProgressDialog dialog
public MyAsyncClass(Activity activity){
this.activity = activity;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Reading data");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected CharSequence doInBackground(Void... params) {
return readEula(activity);
}
protected void onPostExecute(CharSequence data) {
if(dialog!=null && dialog.isShowing())
dialog.dismiss();
final AlertDialog.Builder builder = new AlertDialog.Builder(
activity);
Log.d(TAG, "insideEulaLaunch");
builder.setTitle(R.string.eula_title);
builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.setEulaStatus(context, true);
if (activity instanceof OnEulaAgreedTo) {
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}
}
});
builder.setNegativeButton(R.string.eula_refuse,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
refuse(activity);
}
});
builder.setMessage(data);
builder.create().show();
}
}
then call this class as,
if (!prefs.getEulaStatus(context)) {
MyAsyncClass myAsyncClass = new MyAsyncClass(activity);
myAsyncClass.execute();
}
Correction to your Edit:
in your Eula class,
change this,
MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
public boolean onComplete(String result) {
builder.setMessage(data);
builder.create().show();
return false;
}
}) ;
MyAsync async= new MyAsync(this, activity) ;
async.excecute();
to this,
MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
public boolean onComplete(String result) {
builder.setMessage(data);
builder.create().show();
return false;
}
}) ;
async.excecute();
in your Async class,
change your constructor to,
public MyAsync(Activity activity, TaskCompleteListner taskCompleteListner) {
this.taskCompleteListner = taskCompleteListner;
this.activity=activity;
}

Use this Async Class to get the text
public class MyAsync extends AsyncTask<Void, Void, String>{
TaskCompleteListner taskCompleteListner;
Activity activity;
public interface TaskCompleteListner{
public boolean onComplete(String result);
}
public MyAsync(TaskCompleteListner taskCompleteListner,Activity activity) {
this.taskCompleteListner = taskCompleteListner;
this.activity=activity;
}
#Override
protected String doInBackground(Void... params) {
String data=(String) readEula(activity);
return data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
taskCompleteListner.onComplete(result);
}
private static CharSequence readEula(Activity activity) { //READING FILE HERE
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
buffer.append(line).append('\n');
byte[] latin1 = buffer.toString().getBytes("ISO-8859-1");
return new String(latin1);
//return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
}
You can use this in your Eula class as follows:
if (!prefs.getEulaStatus(context)) {
MyAsync async= new MyAsync(activity,new TaskCompleteListner() {
#Override
public boolean onComplete(String result) {
//TODO show your alert dialog here. Result has the string needed
return false;
}
}) ;
}
Hope this helps.

If its just a dialog u need to show, you can use the Activity's following method:
public final void runOnUiThread (Runnable action)
AsyncTask would be a cleaner approach. However, this will save you the trouble of extra code if you are looking for a quick switch onto the main thread.

Async task will be the better approach.
1. Do your background operation (readEula(Activity activity)) in doInBackGround and
2. show dialog in onPostExecute method.
In another approach create thread and do your operation (readEula(act)) in it and use handler to communicate to this thread and show alert dialog in you activity only.

Related

ProgressDialog inside AsyncTask not showing progress [duplicate]

This question already has answers here:
ProgressDialog in AsyncTask
(7 answers)
Closed 6 years ago.
Though I have checked many references online, I still can't find the problem.
It seems the ProgressDialog appears fine but whenever I want to update the progress, in onProgressUpdate its instance is always null.
This is my AsyncTask:
package com.async_tasks;
public class UploadTask extends AsyncTask<Void,Integer,Void> implements Serializable {
private static final String TAG = UploadTask.class.getSimpleName();
private ConnectionToServer _connectionToServer;
private TransferDetails _td;
private Activity _activity;
private ProgressDialog _progDialog;
private UploadTask _taskInstance;
public UploadTask(Activity activity, ConnectionToServer connectionToServer, TransferDetails td) {
_activity = activity;
_connectionToServer = connectionToServer;
_td = td;
_taskInstance = this;
}
#Override
protected void onPreExecute() {
_progDialog = new ProgressDialog(_activity);
String cancel = _context.getResources().getString(R.string.cancel);
_progDialog.setCancelable(false);
_progDialog.setTitle(_context.getResources().getString(R.string.uploading));
_progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
_progDialog.setProgress(0);
_progDialog.setMax(100);
_progDialog.setButton(DialogInterface.BUTTON_NEGATIVE, cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
_taskInstance.cancel(true);
}
});
_progDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
//uploading file ...
float percent = (float) (fileSize - bytesToRead) / fileSize * 100;
publishProgress((int)percent);
}
}
catch (IOException e) {
// Handling exception
} finally {
if(bis!=null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
clearMembers();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
if(_progDialog!=null) { // <<------------ I suspect for some reason this is always false, as _progDialog is always null - But why?!
_progDialog.incrementProgressBy(progress[0]);
}
}
#Override
protected void onPostExecute(Void result) {
//The task is complete, clear members
clearMembers();
}
private void clearMembers() {
_activity = null;
if(_progDialog!=null) {
_progDialog.dismiss();
_progDialog = null;
}
}
}
And this is the call from MainActivity:
TransferDetails td = (TransferDetails) report.data();
ConnectionToServer conn = StorageServerProxyService.getConn();
UploadTask uploadTask = new UploadTask(MainActivity.this, conn, td);
uploadTask.execute();
Modify the onPreExecute() method as below :
#Override
protected void onPreExecute() {
progDialog = new ProgressDialog(ActivityName.this);
String cancel = _context.getResources().getString(R.string.cancel);
_progDialog.setCancelable(false);
_progDialog.setTitle(_context.getResources().getString(R.string.uploading));
_progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
_progDialog.setProgress(0);
_progDialog.setMax(100);
_progDialog.setButton(DialogInterface.BUTTON_NEGATIVE, cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
_taskInstance.cancel(true);
}
});
_progDialog.show();
}

android array list null

I'm designing an Android app that downloads information from a website and prints a list on-screen with that information in the form of an Array List.
However, the ArrayList I use doesn't load correctly and my screen becomes blank.
Activity code:
Tenda.java
public class Tenda extends Activity implements OnItemClickListener, LocationListener {
ProgressDialog lDialog;
String json_string;
SuperAdapter adapter_super;
int user_id;
private LocationManager locationManager;
public String provider;
private String lattitude , longitude;
/*************************************************/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tenda);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
init_conf();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tenda, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_update:
updateList();
return true;
case R.id.menu_search:
alert_search();
return true;
case R.id.menu_cancel:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
TextView stock = (TextView) view.findViewById(R.id.list_product_stock);
int num_stock = Integer.parseInt(stock.getText().toString()) ;
if(num_stock!=0){
ArrayList<Super> productes=adapter_super.getItems_producte();
Super current_product= productes.get(position);
alert_buy(num_stock,current_product);
}
else
{
Toast.makeText(this, "OUT OF STOCK", Toast.LENGTH_LONG).show();
}
}
private void init_conf(){
Bundle extras = getIntent().getExtras();
user_id = extras.getInt("user_id");
Toast.makeText(this, "user id"+Integer.toString(user_id), Toast.LENGTH_LONG).show();
ListView lsv_producto = (ListView)findViewById(R.id.list_productes);
adapter_super = new SuperAdapter(Tenda.this,null);
lsv_producto.setAdapter(adapter_super);
lsv_producto.setOnItemClickListener(this);
updateList();
}
private void updateList(){
loading();
String url = "http://www.v2msoft.com/clientes/lasalle/curs-android/products.php?user_id="+user_id;
boolean is_con=is_connected();
if(is_con){
Log.i("Connection", "true");
AsyncTask(url);
Toast.makeText(this, "connected internet", Toast.LENGTH_LONG).show();
}
else{
json_string=storeRead();
refreshListByJson(json_string);
Toast.makeText(this, "not connected internet", Toast.LENGTH_LONG).show();
}
}
private void search(String text){
loading();
String url="http://www.v2msoft.com/clientes/lasalle/curs-android/search.php?user_id="+user_id+"&q="+text;
boolean is_con=is_connected();
if(is_con){
Log.i("search URL", url);
Toast.makeText(this, url, Toast.LENGTH_LONG).show();
searchAsyncTask(url);
}
else{
Toast.makeText(this, "NO CONNECTION", Toast.LENGTH_LONG).show();
}
}
private void buy(Super producte, int value){
int product_id= producte.getId();
String url="http://www.v2msoft.com/clientes/lasalle/curs-android/buy.php?user_id="+user_id+
"&product_id="+product_id+
"&items="+value+
"&lat="+1+
"&long="+1;
Toast.makeText(this, url, Toast.LENGTH_LONG).show();
}
private void AsyncTask(String url){
LongAsyncTask task = new LongAsyncTask();
task.execute(url);
}
private void searchAsyncTask(String url){
SearchAsyncTask task = new SearchAsyncTask();
task.execute(url);
}
public void alert_search(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String m_Text = input.getText().toString();
Toast.makeText(getApplicationContext(), m_Text, Toast.LENGTH_LONG).show();
search(m_Text);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void alert_buy(int max_value,final Super producte){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("BUY");
final NumberPicker number= new NumberPicker(this);
number.setMaxValue(max_value);
number.setMinValue(0);
builder.setView(number);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int value= number.getValue();
Toast.makeText(getApplicationContext(), value+"", Toast.LENGTH_LONG).show();
buy(producte,value);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
/*************************ASYNC TASK************************/
public class LongAsyncTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... url) {
String url_result= conect(url[0]);
Log.i("DO IN BACKGROUND", url_result);
return url_result;
}
protected void onPostExecute(String url_result) {
Log.i("On Post EXECUTE", url_result);
json_string= url_result;
storeWrite(json_string);
refreshListByJson(json_string);//line 257
}
}
public class SearchAsyncTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... url) {
String url_result= conect(url[0]);
Log.i("Search result", url_result);
return url_result;
}
protected void onPostExecute(String url_result) {
Log.i("On Post EXECUTE SEARCH", url_result);
json_string= url_result;
Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
refreshListByJson(json_string);
}
}
public class BuyAsyncTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... url) {
String url_result= conect(url[0]);
Log.i("buy result", url_result);
return url_result;
}
protected void onPostExecute(String url_result) {
Log.i("On Post EXECUTE SEARCH", url_result);
json_string= url_result;
Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
}
}
/*************************************************/
private void refreshListByJson(String json){//line 300
lDialog.dismiss();
Store store=Store.newStore(json);
if (store.getProductes() != null)
{
Log.i("store-nom", "" + store.getStore());//line 305
Log.i("store-producte", "" + store.getProductes().toString()); //line 306
adapter_super.setItems_producte(store.getProductes());
}
}
private void storeWrite(String data){
String FILENAME = "json_store";
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("Write STORAGE", data);
}
private String storeRead(){
String FILENAME = "json_store";
FileInputStream fis;
StringBuilder fileContent = new StringBuilder();
try {
fis= openFileInput (FILENAME);
BufferedReader br= new BufferedReader(new InputStreamReader(fis));
String line;
while((line = br.readLine())!= null)
{
fileContent.append(line);
}
br.close();
fis.close();
Log.i("READ STORAGE", fileContent.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fileContent.toString();
}
public String conect(String url_string){
HttpURLConnection con = null;
BufferedReader reader= null;
try{
URL url = new URL(url_string);
con = (HttpURLConnection)url.openConnection();
reader= new BufferedReader(new InputStreamReader(con.getInputStream()));
String line ="";
StringBuffer responseBuffer = new StringBuffer();
while((line=reader.readLine())!=null)
{
responseBuffer.append(line);
}
return responseBuffer.toString();
}
catch(Exception ex){
Log.e(getClass().getName(), ex.getMessage(),ex);
return null;
}
}
public boolean is_connected(){
ConnectivityManager conMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i == null)
return false;
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
return true;
}
private void loading(){
lDialog = new ProgressDialog(this);
lDialog.setMessage("Loading...");
lDialog.setCancelable(false);
lDialog.show();
}
/*** Location ***/
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
int lat = (int) (arg0.getLatitude());
int lng = (int) (arg0.getLongitude());
lattitude = "Lattitude: "+ lat ;
longitude = "Longitude: "+ lng;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
////TODO Auto-generated method stub
}
}
Store.java
public class Store {
private String store;
private ArrayList<Super> productes;
public String getStore() {
return store;
}
public void setSuper(String store) {
this.store = store;
}
public ArrayList<Super> getProductes() {
return productes;
}
public void setProductes(ArrayList<Super> productes) {
this.productes = productes;
}
static Store newStore(String json_string){
Gson gson= new Gson();
Store store = gson.fromJson(json_string,Store.class);
return store;
}
}
}
Super.java
public class Super {
private int id;
private String fabricant;
private String nom;
private float preu;
private int stock;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFabricant() {
return fabricant;
}
public void setFabricant(String fabricant) {
this.fabricant = fabricant;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public float getPreu() {
return preu;
}
public void setPreu(float preu) {
this.preu = preu;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
}
LongAsyncTask.java
public class LongAsyncTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... arg0) {
return null;
}
protected void onPostExecute(String result) {
}
}
SuperAdapter.java
public class SuperAdapter extends BaseAdapter {
public ArrayList<Super> getItems_producte() {
return items_producte;
}
private Activity activity;
private ArrayList<Super> items_producte;
public SuperAdapter(Activity activity, ArrayList<Super> items_producte){
this.activity = activity;
this.items_producte= items_producte;
}
#Override
public int getCount() {
if(items_producte==null){
return 0;
}
else{
return items_producte.size();
} }
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items_producte.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View contentView, ViewGroup Parent) {
// TODO Auto-generated method stub
View view = contentView;
if(view==null){
LayoutInflater inflate =(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflate.inflate(R.layout.info_product, null,false);
}
Super item_producte = items_producte.get(position);
TextView id = (TextView)view.findViewById(R.id.list_product_id);
TextView fabricant = (TextView)view.findViewById(R.id.list_product_fabricant);
TextView nom = (TextView)view.findViewById(R.id.list_product_nom);
TextView preu = (TextView)view.findViewById(R.id.list_product_preu);
TextView stock = (TextView)view.findViewById(R.id.list_product_stock);
id.setText(Integer.toString(item_producte.getId()));
fabricant.setText(item_producte.getFabricant());
nom.setText(item_producte.getNom());
preu.setText(Float.toString(item_producte.getPreu()));
stock.setText(Integer.toString(item_producte.getStock()));
fabricant.setTextColor(activity.getResources().getColor(R.color.fabricant));
nom.setTextColor(activity.getResources().getColor(R.color.fabricant));
preu.setTextColor(activity.getResources().getColor(R.color.fabricant));
stock.setTextColor(activity.getResources().getColor(R.color.fabricant));
if(position%2==0){
view.setBackgroundColor(activity.getResources().getColor(R.color.files_parelles));
}
else{
view.setBackgroundColor(activity.getResources().getColor(R.color.files_imparelles));
}
/*STOCK COLOR*/
if(item_producte.getStock()<=0){
view.setBackgroundColor(activity.getResources().getColor(R.color.stock_null_bg));
fabricant.setTextColor(activity.getResources().getColor(R.color.stock_null_tx));
nom.setTextColor(activity.getResources().getColor(R.color.stock_null_tx));
preu.setTextColor(activity.getResources().getColor(R.color.stock_null_tx));
stock.setTextColor(activity.getResources().getColor(R.color.stock_null_tx));
}
return view;
}
public void setItems_producte(ArrayList<Super> items_producte) {
this.items_producte = items_producte;
this.notifyDataSetChanged();
}
}
The main problem is located in this section:
private void refreshListByJson(String json){//line 300
lDialog.dismiss();
Store store=Store.newStore(json);
if (store.getProductes() != null)
{
Log.i("store-nom", "" + store.getStore());//line 305
Log.i("store-producte", "" + store.getProductes().toString()); //line 306
adapter_super.setItems_producte(store.getProductes());
}
}
The "if" condition is not fulfilled: store.getProductes() is null.
It's strange because the app can DL the info from internet and I can see that in the logcat output: for some reason it doesn't load into the ArrayList.
Could you please help me in figuring out what I must do for the ArrayList to work?
Thank you very much.
ListView lsv_producto = (ListView)findViewById(R.id.list_productes);
adapter_super = new SuperAdapter(Tenda.this,null);
lsv_producto.setAdapter(adapter_super);
You are passing null in SuperAdapter cnstructer, you need to pass ArrrayList instead of passing null.
Put condition this way
if (store.getProductes() != null && store.getProductes().size()>0){
}
private ArrayList<Super> productes = new ArrayList<Super>():
You never use your setProducts too so this will be empty.
First Remove the below code
ListView lsv_producto = (ListView)findViewById(R.id.list_productes);
adapter_super = new SuperAdapter(Tenda.this,null);
lsv_producto.setAdapter(adapter_super);
Now modified the refreshListByJson() as below
private void refreshListByJson(String json){//line 300
lDialog.dismiss();
Store store=Store.newStore(json);
if (store.getProductes() != null)
{
Log.i("store-nom", "" + store.getStore());//line 305
Log.i("store-producte", "" + store.getProductes().toString()); //line 306
adapter_super.setItems_producte(store.getProductes());
}
//////////////////
ListView lsv_producto = (ListView)findViewById(R.id.list_productes);
adapter_super = new SuperAdapter(Tenda.this,store.getProductes());
lsv_producto.setAdapter(adapter_super);
////////////////////
}

Android AsyncTask Dialog fast close

My code:
private class selectBookInAutor extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
arr_book_title.clear();
arr_book_href.clear();
mProgressDialog = new ProgressDialog(_context);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
StringBuilder sb = new StringBuilder();
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
Elements links = doc.select("li>a");
for (Element link : links) {
sb.append(link.text());
arr_book_title.add(link.text());
arr_book_href.add(Jsoup.clean(link.attr("abs:href"), Whitelist.basic()));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
final CharSequence[] items = arr_book_title.toArray(new CharSequence[arr_book_title.size()]);
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
}else if(seletedItems.contains(indexSelected)){
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
for (Object s : seletedItems){
String[] separated = selGroupParam.split(";");
String _idautor = separated[0].toString();
long id_book = db.insertBOOK(_idautor, arr_book_href.get(Integer.valueOf(s.toString())).toString(), "", arr_book_title.get(Integer.valueOf(s.toString())).toString());
new **saveBookInAutor().execute(arr_book_href.get(Integer.valueOf(s.toString())).toString(), _idautor, String.valueOf(id_book));**
}
refreshList();
}
}).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog.dismiss();
}
}
private class saveBookInAutor extends AsyncTask<String, Void, String> {
String _idautor, _idbook;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog2 = new ProgressDialog(_context);
mProgressDialog2.setMessage("Save to file");
mProgressDialog2.setIndeterminate(false);
mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[1];
_idbook = params[2];
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
_html = doc.select("dd").outerHtml();
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
Toast.makeText(_context, "Save file", Toast.LENGTH_SHORT).show();
String html = "<html lang='ru'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>"+result+"</body></html>";
//String html = result;
**savePageToFile(_idautor + "_" + String.valueOf(_idbook), html);**
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog2.dismiss();
}
}
public void refreshList() {
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
}
public void savePageToFile(String filename, String html) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_context.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(html);
outputStreamWriter.close();
}
catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
}
}
When you select a page and clicking "Ok" ProgressDialog mProgressDialog2 opens and displays just a 1 second. Because of this, I do not see the download Page or not.
How to make mProgressDialog2 displayed all the while to save the page as a file?
Thank you!
UPD
What i want is :
Start mProgressDialog.
After downloading the page disappears and AlertDialog comes with the question what to choose.
After choosing, mProgressDialog2 should be displayed as long as it downloads and saves the file in the webpage.
However mProgressDialog2 disappears in 1 second, and process of saving the file goes on in silence.
In your onPostExecute method, you unconditionally call
mProgressDialog2.dismiss();
This is closing the dialog immediately after it is displayed. That call should be moved to the handler code for each of the buttons. (i.e.the onClick method for the positive and negative buttons)
in onPostExecute(), compare Strings like
if(!result.equals(""))
and try once.
use equals() method for String comparisons.

show progress dialog while loading data

I want to show a progress dialog while loading some data from remote server :
I'm using the following thread in order to get the data and it's working, but i'm not able to show the progress bar on the activity:
public class Request {
public String text ;
public boolean downloadText(String urlStr) {
final String url = urlStr;
new Thread () {
public void run() {
int BUFFER_SIZE = 2000;
InputStream in = null;
Message msg = Message.obtain();
msg.what=2;
try {
in = openHttpConnection(url);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
text = "";
char[] inputBuffer = new char[BUFFER_SIZE];
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
text += readString;
inputBuffer = new char[BUFFER_SIZE];
}
Bundle b = new Bundle();
b.putString("text", text);
msg.setData(b);
in.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
would you please tell me how can i do it !!
create the class as below and just call the object of this class.
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog Asycdialog = new ProgressDialog(ActivityName.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
Asycdialog.setMessage("Loading...");
Asycdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// do the task you want to do. This will be executed in background.
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Asycdialog.dismiss();
}
}
Use progressDialog
final ProgressDialog progress=ProgressDialog.show(youractivity.this,"","message");
new Thread()
{
public void run()
{
try{
youractivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
// your code
}
});
}
catch(Exception e)
{
}
progress.dismiss();
}
}.start()
Also, note that if you want to use Toast, you should use runOnUiThread
If you do not want to change the structure of your code, you can use runOnUiThread or an Handler to show and dissmiss the progress dialog. Show it when the firs line of the run method is excuted and dismiss it in the finally block.
public void run() {
runOnUiThread(new Runnable() {
public void run(){
// show progress dialog
}
});
/// your code here
try {
} catch (IOException e) {
} finally {
runOnUiThread(new Runnable() {
public void run(){
// dismiss progress dialog
}
});
}
}
Create Progress Dialog in AsyncTask
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
protected void onPostExecute(Void result) {
// do UI work here
}
}
pDialog = ProgressDialog.show(context, null, "Loading...", true);
pDialog.setCancelable(false);
new Thread() {
public void run() {
// handle the exception somehow, or do nothing
// run code on the UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
// do yor ui part here
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}.start();

Making an Asynchronous requests within a Android services

in my Service I am using http://loopj.com/android-async-http/
within the doInBackground() method of a service. Because it's asynchronous, the method finishes before the callbacks are called, and therefore onPostExecute is being called and shutting the service down... How can I avoid this?
public class LoginService extends AsyncTask<String, Void, LoginService.LoginStatus> {
private static String TAG = "x-LoginService";
private ProgressDialog progressDialog;
private AlertDialog dialog = null;
private final Context context;
public LoginService(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", context.getString(R.string.waitingLogin), true);
}
#Override
protected void onPostExecute(LoginStatus loginStatus) {
progressDialog.dismiss();
Log.d(TAG, "--STARTONPOSTEXECUTE");
String message;
LocalSettingsService settings = new LocalSettingsService(context);
if (loginStatus == LoginStatus.LOGGED_IN) {
settings.put("loggedIn", "true");
Intent intent = new Intent(context, FragmentTabs.class);
context.startActivity(intent);
//Intent intent = new Intent(context, SummaryPage.class);
//Intent intent = new Intent(context, FeedbackPage.class);
//Intent intent = new Intent(context, NavTab.class);
//context.startActivity(intent);
return;
} else if (loginStatus == LoginStatus.INVALID_CREDENTIALS) {
settings.put("loggedIn", "false");
message = context.getString(R.string.invalidCredentials);
} else {
settings.put("loggedIn", "false");
message = context.getString(R.string.serverError);
}
dialog = new AlertDialog.Builder(context)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(context.getString(R.string.errorTitle))
.setMessage(message)
.setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create();
dialog.show();
}
#Override
protected LoginStatus doInBackground(String... strings) {
String username = strings[0];
String password = strings[1];
doLogin();
return LoginStatus.LOGGED_IN;
}
private void doLogin() {
{
Log.d(TAG, "--STARTDOLOGIN");
RequestParams params = new RequestParams();
params.put("username", "un");
params.put("password", "pw");
ServicesRestClient.post("ajax/login", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(String s) {
Log.d(TAG, "--ONSUCCESS");
}
#Override
public void onFailure(Throwable throwable, String s) {
Log.d(TAG, "--ONFAILURE");
}
});
}
}
public void onPause() {
if (dialog != null) {
dialog.dismiss();
}
}
public static enum LoginStatus {
LOGGED_IN, INVALID_CREDENTIALS, SERVER_SIDE_ERROR
}
}
I think you this code too much complicated. In general you should somehow stay in doInBackground() unless you service ends, but not knowing the internals of what you use I can tell how to do it best. But since this library you use announces to be doing asynchronous networking, I'd not use another async task in first place

Categories

Resources