How to show message in showDialog();
I want when freshDownloadView is finished show showDialog.
My code is as follows:
public class MainActivity extends Activity implements View.OnClickListener {
private FreshDownloadView freshDownloadView;
private Button btDownloaded;
private TextView btReset;
private TextView btDownloadError;
private final int FLAG_SHOW_OK = 10;
private final int FLAG_SHOW_ERROR = 11;
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int progress = (int) msg.obj;
freshDownloadView.upDateProgress(progress);
switch (msg.what) {
case FLAG_SHOW_OK:
break;
case FLAG_SHOW_ERROR:
freshDownloadView.showDownloadError();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
freshDownloadView = (FreshDownloadView) findViewById(R.id.pitt);
btDownloaded = (Button) findViewById(R.id.bt_downloaded);
btReset = (Button) findViewById(R.id.bt_reset);
btDownloadError = (Button) findViewById(R.id.bt_download_error);
btDownloaded.setOnClickListener(this);
btReset.setOnClickListener(this);
btDownloadError.setOnClickListener(this);
}
this is button freshDownload
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_downloaded:
if (freshDownloadView.using()) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = Message.obtain();
message.obj = i;
handler.sendMessage(message);
showDialog();
}
}
}).start();
break;
case R.id.bt_reset:
freshDownloadView.reset();
break;
case R.id.bt_download_error:
if (freshDownloadView.using()) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 30; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = Message.obtain();
if (i == 30) {
message.what = FLAG_SHOW_ERROR;
}
message.obj = i;
handler.sendMessage(message);
}
}
}).start();
break;
}
}
public void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setMessage(R.string.download_app)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create().show();
}
protected void onPause() {
// unregisterReceiver(receiver);
super.onPause();
}
protected void onResume() {
// registerReceiver(receiver, new IntentFilter(
// WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
}
I suggest you use AsyncTask for this. You can initiate the download in the doInBackground method and show the alert dialog (as needed) in the onPostExecute method. This will also free you from using Thread.sleep(100) which isn't a good practice on Android.
However, if you still prefer to use the FreshDownloadView please update your question with the code for FreshDownloadView and we can suggest something.
Related
I would like to update the progressBar with Handler and for loop but without success.
Code:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(progress_k, 100);
}
}, 2000);
}
}
Question:
The progress bar increase immediately to the end value instead of progressively.
Why?
Try this:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
final int curr_progress_k = progress_k;
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(curr_progress_k, 100);
}
}, progress_k * 100); // adjust "100" value to adjust speed
}
}
Repeat a task with a time delay?
#inazaruk
private ProgressBar progressBar;
private Handler mHandler;
private int progressInt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
progressBar = (ProgressBar) findViewById(R.id.pb);
progressBar.setProgress(0);
mHandler = new Handler();
runnable.run();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
updateProgress();
} catch (Exception ignored) {
} finally {
mHandler.postDelayed(runnable, progressInt);
}
}
};
private void updateProgress() {
progressInt += 1;
if (progressInt > 100) {
mHandler.removeCallbacks(runnable);
} else {
progressBar.setProgress(progressInt);
}
}
try this code:
Solution 1
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler();
class Task implements Runnable {
int start,end;
Task(int a,int b) { start = a; end = b;}
#Override
public void run() {
for (int i =start ; i <= end; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler1.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(value);
}
});
}
}
}
Thread t = new Thread(new Task(from, to)); //call it
t.start();
}
Solution 2: More Simple
If thread is too much to ask for this problem..
you can use the following solution to use a single Handler to update progressbar:
code
public class HandlerDemo extends Activity
{
ProgressBar bar;
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
bar.incrementProgressBy(5);
}
};
boolean isRunning = false;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progress);
}
public void onStart()
{
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
for (int i = 0; i < 20 && isRunning; i++)
{
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t)
{
// just end the background thread
}
}
});
isRunning = true;
background.start();
}
public void onStop()
{
super.onStop();
isRunning = false;
}
}
Hope it helps..
When my first to get the data from the first tab of fragment,it was something wrong.And through the web page to open it ,these data is normal.
public class OnlineAllInsuranceFragment extends Fragment implements OnListViewListener {
private ScrollListView MainView;
private BasicAdapter2 Adapter;
private Integer Step=10;
private Integer Start=0;
private Integer End=Step;
private Handler handler,handler2;
private DataTable dTable;
public static String SelectCode="";
private static final int OVER = 1;
private String polnum;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_online_insurance,container,false);
handler2 = new Handler();
new Thread(new Runnable() {
public void run() {
Looper.prepare();
handler2.post(runSetList);
Looper.loop();
}
}).start();
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.MainView=(ScrollListView)getView().findViewById(R.id.contractlistView1);
this.MainView.setPullLoadEnable(true);
this.MainView.setXListViewListener(this);
}
private void SetList(){
Start=0;
End=3;
this.dTable = new DataTable(getActivity(),"newcontract");
this.dTable.Load("AgentCode="+OnlineAllInsuranceFragment.SelectCode+"&Start=0&End="+Step);
if(dTable.GetRowCount()>0){
this.MainView.setVisibility(0);
this.StartData(this.dTable.GetList(),R.layout.userlistitem4);
}else{
this.MainView.setVisibility(8);
TextView NullView=(TextView) getView().findViewById(R.id.listViewNull1);
NullView.setVisibility(0);
NullView.setHeight(50);
}
}
private void StartData(ArrayList<Map<String, Object>> List, int Resource) {
this.Adapter = new BasicAdapter2(getActivity(), List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },
new int[] {R.id.contractitem_label_Provider,
R.id.contractitem_label_ProdName,
R.id.contract_label_cno,
R.id.contractitem_label_contractNo,
R.id.contractitem_label_acceptTime,
R.id.contractitem_label_contractStatus,
R.id.contractitem_label_premium,
R.id.contractitem_label_feilv,
R.id.contractitem_label_receivedPremium,
R.id.contractitem_label_Name },
new int[] {R.id.listitem_button_look, R.id.listitem_button_pay,
R.id.listitem_main1,R.id.contractitem_label_companyImage,R.id.contractitem_label_payImage },
new BasicAdapter2.ListAdapterListener() {
#Override
public void onClickAtOKButton(View v) {
String company = dTable.GetValue((Integer)v.getTag(), 1).toString();//产品名
String status = dTable.GetValue((Integer)v.getTag(), 4).toString();//保单状态
switch (v.getId()) {
case R.id.listitem_button_pay:
polnum = dTable.GetValue((Integer)v.getTag(), 3).toString();
String numPol = dTable.GetValue((Integer)v.getTag(), 2).toString();//是“保单号”还是“投保单号”
if (numPol.contains("aa")) {
Intent intent = new Intent();
intent.setClass(getActivity(),PolicyInformationActivity.class);
intent.putExtra("polnum", polnum);
startActivity(intent);
} else if (numPol.contains("bb")) {
toastDialog();
}
break;
case R.id.listitem_button_look:
Toast.makeText(getActivity(),"...", Toast.LENGTH_SHORT).show();
LogUtil.e("company+status", company+"=="+status);
break;
case R.id.listitem_main1:
break;
}
}
},
new BasicAdapter2.VisibleAdapterListener() {
#Override
public int onSetVisible(View v) {
String company = dTable.GetValue((Integer)v.getTag(), 1).toString();//产品名
String status = dTable.GetValue((Integer)v.getTag(), 4).toString();//保单状态
LogUtil.e("status","=="+status);
int drawId;
switch (v.getId()) {
case R.id.contractitem_label_companyImage:
if ( company.contains("cc") ) {
drawId = R.drawable.taikang2x;
return drawId;
} else if (company.contains("dd") ) {
drawId = R.drawable.youban2x;
return drawId;
}
break;
case R.id.contractitem_label_payImage:
if ( status.equals("ee") ) {
drawId = R.drawable.security2x;
return drawId;
} else if (status.equals("ff")) {
drawId = R.drawable.nopay2x;
return drawId;
} else if ( status.equals("gg")) {
drawId = R.drawable.invalid2x;
return drawId;
}
break;
case R.id.listitem_button_pay:
if (company.contains("hh") && status.equals("ii")) {
return 0;
} else if (company.contains("jj") || status.equals("kk")) {
return 4;
}
break;
}
return 99;
}
});
handler = new Handler();
this.Adapter.Start(this.MainView);
this.Start += Step;
this.End += Step;
}
private void LoadData(){
this.dTable.Load("AgentCode="+OnlineAllInsuranceFragment.SelectCode+"&Start="+Start+"&End="+End);
this.Start += Step;
this.End += Step;
}
private void stopRefresh() {
this.MainView.stopRefresh();
this.MainView.setRefreshTime("just");
}
private void stopLoadMore() {
this.MainView.stopLoadMore();
}
#Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
SetList();
stopRefresh();
}
}, 2000);
}
#Override
public void onLoadMore() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
LoadData();
stopLoadMore();
}
}, 2000);
}
#SuppressLint("HandlerLeak")
Handler handler1 = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case OVER:
Control.ExitDialog();
break;
default:
break;
}
super.handleMessage(msg);
}
};
Runnable runSetList = new Runnable() {
#Override
public void run() {
SetList();
}
};
private void toastDialog() {
CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
builder.setTitle("xx");
builder.setMessage("yy");
builder.setNegativeButton("vv", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton("ww", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Control.StartDialog(getActivity());
new Thread(new Runnable() {
public void run() {
Looper.prepare();
startActivity(new Intent(getActivity(),HomeActivity.class));
send();
handler1.sendEmptyMessage(1);
Looper.loop();
}
}).start();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.setCancelable(false);
noticeDialog.setCanceledOnTouchOutside(false);
noticeDialog.show();
}
private void send() {
}
}
And when I keep away from this Fragment then comeback,the data become normal,too.The data is not normal just when my first in the Fragment.
I have been spending couple hours to try to update the textview inside the dialog, but failed.
When the option is clicked, there are new dialog is shown, and inside the dialog, there are textviews and button, when I click the button, the textview will be update.
Here is the code related to the button onClick listener:
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
final String currentNum = String.valueOf(i + 1);
Thread t = new Thread() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(currentNum); //it is fine
currentNum.setText(currentNum); //it is the problem, the setText only work when the for loop is finished.
}
});
}
};
t.start();
}
}
});
Please let me know if you need more information. Thanks a lot in advance!
//it is a optionmenu
case R.id.action_refresh:
final TextView currentNum;
final ImageButton start;
String currentNum = Integer.toString(songList.size());
final Dialog lyricsAnalysis = new Dialog(this,R.style.cust_dialog);
lyricsAnalysis.requestWindowFeature(Window.FEATURE_NO_TITLE);
lyricsAnalysis.setContentView(R.layout.analysis);
lyricsAnalysis.setCancelable(true); //back button to cancel
lyricsAnalysis.setCanceledOnTouchOutside(true);
start = (ImageButton) lyricsAnalysis.findViewById(R.id.start);
//first value
currentNum.setText(String.valueOf(currentNum));
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTextView(lyricsAnalysis,i);
}
}
});
lyricsAnalysis.show();
lyricsAnalysis.getWindow().setLayout(600, 1000);
break;
}
return super.onOptionsItemSelected(item); }
public void updateTextView(Dialog dialog, int i) {
final TextView currentNum = (TextView) dialog.findViewById(R.id.currentNum);
currentNum.setText(Stri`enter code here`ng.valueOf(i));
//return;
}
Try this method. This may helps you. It's work for me.(But I am not use this in dialog)
public void updateTextView(String toThis) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(toThis);
//return;
}
try like this
int elapsedtime=0;
boolean isTimerRunning=false;
Timer timerr;
inside onCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//declare your textview here;
timerr=new Timer();
startTimer();
}
/*
* timer for displaying message bubble
*/
protected static void startTimer() {
isTimerRunning = true;
elapsedtime = 0;
// recordingseek.setProgress(0);
timerr.scheduleAtFixedRate(new TimerTask() {
public void run() {
// increase every sec
elapsedtime++;
mmHandler.obtainMessage(1).sendToTarget();
System.out.println("recording time" + elapsedtime);
if(elapsedtime==50)
timerr.cancel();
}
}, 1000, 2000);
};
public static Handler mmHandler = new Handler() {
public void handleMessage(Message msg) {
textview.setText(elapsedtime);
}
};
}
};
Hi in the below code After clicking login button with internet working fine.suppose there is no internet connection it's not working I want to show diaglog there is no internet connection.
Can any one help me from this issue.
Login1.java
public class Login1 extends Activity {
protected static final int NOT_CONNECTED_TO_SERVICE = 0;
protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
public static final String AUTHENTICATION_FAILED = "0";
public static final String FRIEND_LIST = "FRIEND_LIST";
protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2 ;
protected static final int NOT_CONNECTED_TO_NETWORK = 3;
private EditText usernameText;
private EditText passwordText;
private Button cancelButton;
private IAppManager imService;
public static final int SIGN_UP_ID = Menu.FIRST;
public static final int EXIT_APP_ID = Menu.FIRST + 1;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
if (imService.isUserAuthenticated() == true)
{
Intent i = new Intent(Login1.this, FriendList.class);
startActivity(i);
Login1.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(Login1.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
Boolean isInternetPresent = false;
ConnectionDetector cd;
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(Login1.this, IMService.class));
setContentView(R.layout.login_screen);
setTitle("Login");
Button loginButton = (Button) findViewById(R.id.login);
cancelButton = (Button) findViewById(R.id.cancel_login);
usernameText = (EditText) findViewById(R.id.userName);
passwordText = (EditText) findViewById(R.id.password);
loginButton.setOnClickListener(new OnClickListener(){
#SuppressWarnings("deprecation")
public void onClick(View arg0)
{
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login1.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
if (imService == null) {
Toast.makeText(getApplicationContext(),R.string.not_connected_to_service, Toast.LENGTH_LONG).show();
return;
}
else if (imService.isNetworkConnected() == false)
{
Toast.makeText(getApplicationContext(),R.string.not_connected_to_network, Toast.LENGTH_LONG).show();
showDialog(NOT_CONNECTED_TO_NETWORK);
}
else if (usernameText.length() > 0 &&
passwordText.length() > 0)
{
Thread loginThread = new Thread(){
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(usernameText.getText().toString(), passwordText.getText().toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null || result.equals(AUTHENTICATION_FAILED))
{
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),R.string.make_sure_username_and_password_correct, Toast.LENGTH_LONG).show();
}
});
}
else {
handler.post(new Runnable(){
public void run() {
Intent i = new Intent(Login1.this, FriendList.class);
startActivity(i);
Login1.this.finish();
}
});
}
}
};
loginThread.start();
}
else {
Toast.makeText(getApplicationContext(),R.string.fill_both_username_and_password, Toast.LENGTH_LONG).show();
}
}
});
cancelButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
imService.exit();
finish();
}
});
}
#Override
protected Dialog onCreateDialog(int id)
{
int message = -1;
switch (id)
{
case NOT_CONNECTED_TO_SERVICE:
message = R.string.not_connected_to_service;
break;
case FILL_BOTH_USERNAME_AND_PASSWORD:
message = R.string.fill_both_username_and_password;
break;
case MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
message = R.string.make_sure_username_and_password_correct;
break;
case NOT_CONNECTED_TO_NETWORK:
message = R.string.not_connected_to_network;
break;
default:
break;
}
if (message == -1)
{
return null;
}
else
{
return new AlertDialog.Builder(Login1.this)
.setMessage(message)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.create();
}
}
#Override
protected void onPause()
{
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume()
{
bindService(new Intent(Login1.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, SIGN_UP_ID, 0, R.string.sign_up);
menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);
return result;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId())
{
case SIGN_UP_ID:
Intent i = new Intent(Login1.this, SignUp.class);
startActivity(i);
return true;
case EXIT_APP_ID:
cancelButton.performClick();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login1.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
Add this function
public static boolean CheckInternet(Context context) {
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return wifi.isConnected() || mobile.isConnected();
}
This function check the wifi or the mobile network if available and return true if yes false if no
and replace this:
if (!isInternetPresent) {
showAlertDialog(Login1.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
By this code:
if (!CheckInternet(this)) {
new AlertDialog.Builder(this)
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
return;
}
as you said :
I want to show diaglog there is no internet connection.
Use this function :
public static boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
and in your code check internet connection :
if (!isNetworkAvailable()) {
// show your dialog here
}
I want to show custom Crouton alert with a progress bar and I want to update the progress dynamicly. This is my code but it doesn't work. How can i do that? Or how can show progress bar while image uploading
private void showCustomViewCrouton() {
// try {
View view = getLayoutInflater().inflate(R.layout.crouton_custom_view,null);
pB = (ProgressBar) view.findViewById(R.id.progressBar1);
final Crouton crouton;
final Configuration croutonConfig = new Configuration.Builder()
.setDuration(Configuration.DURATION_INFINITE)
.setInAnimation(android.R.anim.fade_in)
.setOutAnimation(android.R.anim.fade_out).build();
crouton = Crouton.make(this, view, R.id.croutonContainer, croutonConfig);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
crouton.hide(crouton);
}
});
crouton.show();
try{
do{
Thread.sleep(100);
deger+=1;
pB.setProgress(deger);
}while(deger<101);
}catch(Exception e){
}
}
Here is how I did it
final ProgressBar progressBar = new ProgressBar(this,null,android.R.attr.progressBarStyleHorizontal);
progressBar.setIndeterminate(false);
Crouton ct = Crouton.make(this,progressBar);
ct.show();
/* Update it While Showing */
Thread progressUpdateThread = new Thread(new Runnable()
{
#Override
public void run()
{
for(int i=0;i<100;i++)
{
final int progress = i;
runOnUiThread(new Runnable()
{
#Override
public void run()
{
progressBar.setProgress(progress);
}
});
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
});
progressUpdateThread.start();
i want to share my new code. I inflate a custom Crouton. I wrote this with using #Kirtan Patel ' s code. thanks him again.
private void showCustomViewCrouton() {
// try {
View view = getLayoutInflater().inflate(R.layout.crouton_custom_view,null);
pB = (ProgressBar) view.findViewById(R.id.progressBar1);
final Crouton crouton;
final Configuration croutonConfig = new Configuration.Builder()
.setDuration(Configuration.DURATION_INFINITE)
.setInAnimation(android.R.anim.fade_in)
.setOutAnimation(android.R.anim.fade_out).build();
crouton = Crouton.make(this, view, R.id.croutonContainer, croutonConfig);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
crouton.hide(crouton);
}
});
crouton.show();
try{
Thread progressUpdateThread = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 100; i++) {
final int progress = i;
runOnUiThread(new Runnable() {
#Override
public void run() {
pB.setProgress(progress);
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
progressUpdateThread.start();
}catch(Exception e){
}
}