Android - Progress Dialog - android

I'm a having a problem. I want to make a progress dialog while my app download some news from a feed.
This is my code at the moment:
public class NyhedActivity extends Activity {
String streamTitle = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nyheder);
TextView result = (TextView)findViewById(R.id.result);
try {
URL rssUrl = new URL("http://rss.tv2sport.dk/rss/*/*/*/248/*/*");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
result.setText(streamTitle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.setText("Cannot connect RSS!");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.setText("Cannot connect RSS!");
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.setText("Cannot connect RSS!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.setText("Cannot connect RSS!");
}
}
private class RSSHandler extends DefaultHandler
{
final int stateUnknown = 0;
final int stateTitle = 1;
int state = stateUnknown;
int numberOfTitle = 0;
String strTitle = "";
String strElement = "";
#Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
strTitle = "Nyheder fra ";
}
#Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
strTitle += "";
streamTitle = "" + strTitle;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("title"))
{
state = stateTitle;
strElement = "";
numberOfTitle++;
}
else
{
state = stateUnknown;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("title"))
{
strTitle += strElement + "\n"+"\n";
}
state = stateUnknown;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
String strCharacters = new String(ch, start, length);
if (state == stateTitle)
{
strElement += strCharacters;
}
}
}
}
I can't figure out how to use the progress dialog. Is it possible for anyone to show my where to define the progressdialog and least but not most how to implement it.
I've looked a lot of places, but everyone seems to do it different ways, and I can't get any of them to work :(
I've even tried to make a fake one which runs on sleep, but I can't figure out what I'm doing wrong.

My preferred way:
class MyActivity extends Activity{
final static int PROGRESS_DIALOG = 1;
ProgressDialog dialog;
#Override
protected Dialog onCreateDialog(int id){
switch(id){
case PROGRESS_DIALOG:
dialog = new ProgressDialog(this);
dialog.setMessage("Whatever you want to tell them.");
dialog.setIndeterminate(true);
dialog.setCancelable(true); // if you want people to be able to cancel the download
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog)
{
**** cleanup. Not needed if not cancelable ****
}});
return dialog;
default:
return null;
}
}
When you want it to appear, you can do showDialog(PROGRESS_DIALOG) and when you want it to go away you can do dialog.dismiss().

Don't do any long-running stuff like network IO in the UI thread (that's what calls your onCreate()), Android will force close your app. Use an AsyncTask instead, check out the linked javadoc for an example.
Create and show your progress dialog in onPreExecute() and keep a reference to it in a field
Update progress by calling publishProgress() from your doInBackground() and handle that in onProgressUpdate(), e.g. like the example linked above
Close your progress dialog and update your UI (text fields, etc.) in onPostExecute()
To create the dialog in onPreExecute(), pass a Context to your AsyncTask constructor, e.g. your activity this and store it in a field.
If you want your data to survive orientation changes or persist across activity restarts, let your AsyncTask write your parsed data into a SQLite database and then display it only the database contents in your activity.
As for the actual "showing a progress dialog" part, use one of its static factory methods show(...):
ProgressDialog dialog = ProgressDialog.show(
this, // a context, e.g. your activity
"Downloading...", // title
"Downloading RSS feed.", // message
);
This will create and show a dialog in one step.

Related

Start new activity when Url finishes loading

I am loading a certain Url into a WebView . This is a login page and the user gets authenticated. When Authenticated he is shown a certain page. At this point I want to stop the Webview loading and start a new activity.
To do this, Iam catching the redirected url and comparing it with a String with my values if it matches then I stop the page loading. But the String Iam trying to compare with the url occurs twice. First when the page starts loading and second when the page complately finishes loading.I want to compare to the second one
But this does not start the new activity.
This is what I have tried:-
myWebView.loadUrl(url);
final ProgressDialog progressBar = ProgressDialog.show(Details1.this, "Loading..", "Please wait!");
myWebView.setWebViewClient(new WebViewClient()
{
private Object progress;
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar!=null && progressBar.isShowing())
{
progressBar.dismiss();
}
url= view.getUrl();
redirected= Uri.decode(url);
/*AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Details1.this);
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder
.setMessage(redirected)
.setCancelable(false)
.setNegativeButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();*/
if(redirected!=null && redirected.contains(endpointHost+"/AuthorizeDevice/index/"+deviceId))
{
Utility.ProgressDialogFragment progDialog = new Utility.ProgressDialogFragment();
progDialog.show(getFragmentManager(), "Wait");
myWebView.stopLoading();
String authorizationContentString = AuthenticateDeviceEndPoint+ "?encodedAccountName=" + encodedAccountName + "&deviceId=" + deviceId + "&hostUrl=" + hostUrl;
authorizationContentString =authorizationContentString.replace("|", "%7C");
//UserInformation userInfo;
JSONParser parser = new JSONParser();
Object register;
try
{
//userInfo
// String responseData= new AuthenticateDevice(Details1.this,myprogressDialog).execute(authorizationContentString).get();
String responseData = new AuthenticateDevice(Details1.this, progDialog).execute(authorizationContentString).get();
register = parser.parse(responseData);
org.json.simple.JSONObject authDevice = (org.json.simple.JSONObject) register;
//Convert Json objects to strings
usersname = (String) authDevice.get("FirstName");
AuthenticationInformation authInfo = new AuthenticationInformation(Details1.this);
authInfo.SetUserInformation(username );
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ExecutionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent myIntent = new Intent(Details1.this, Home.class);
myIntent.putExtra("UsersName", usersname);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
finish();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}

Update array of progressbar in asynctask

I have an asynctask in which I pass an array of progressbars as a parameter. In the doinbackground method, I compute the progress of each progressbar and make a call to PublishProgress with progress as parameter. This is how I have done:
static volatile int currentProgressBarIndex;
#Override
protected Integer doInBackground(String... arg0) {
// TODO Auto-generated method stub
// display the images in now playing
while (ScheduleManager.isScheduleRunning) {
Iterator iterator = nowPlayingMediaSet.entrySet().iterator();
// set images on now playing
for (int i = 0; i < btnImgNowPlaying.length && iterator.hasNext(); ++i) {
Map.Entry mEntry = (Map.Entry) iterator.next();
Show mShowNowPlaying = (Show) mEntry.getKey();
// get show status
currentProgressBarIndex = i;
mProgressStatus[i] = ScheduleManager
.getCurrentPlayingShowStatus(mShowNowPlaying);
// Update the progress bar
publishProgress(mProgressStatus[i]);
}
// sleep 20 second to show the progress
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Integer... progress) {
// TODO Auto-generated method stub
this.progBar[currentProgressBarIndex].setProgress(progress[0]);
}
What happens is that, only my last progressbar in the array is updated. Rest are updated, but later on.. I am sure I am doing something wrong here..

Updating the Progress Bar in the list view

I have a scenario, In my chat application I want to send photos, photos sending takes time. I have attached a progress bar( horizontal) to show the progress of sending the photo in my application. But I am unable to update the progress bar as it is the item of the custom list view.
Here is my asynchtask to set the progress for Progress Bar but I am not able to get it.
class SendPhotoToFriend extends AsyncTask<String, String, String>{
String receiver,path = "";
public SendPhotoToFriend(String path,String receiver) {
// TODO Auto-generated constructor stub
this.path = path;
this.receiver = receiver;
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(connection);
if (sdm == null)
sdm = new ServiceDiscoveryManager(connection);
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
// Create the file transfer manager
FileTransferManager manager = new FileTransferManager(
connection);
FileTransferNegotiator.setServiceEnabled(connection, true);
// Create the outgoing file transfer
OutgoingFileTransfer transfer = manager
.createOutgoingFileTransfer(receiver + "/Smack");
System.out.println("Receiver of the file is "+receiver+"/smack");
Log.i("transfere file", "outgoingfiletransfer is created");
try {
long total = 0;
OutgoingFileTransfer.setResponseTimeout(30000);
transfer.sendFile(new File(path), "Description");
Log.i("transfere file", "sending file");
while (!transfer.isDone()) {
//Thread.sleep(1000);
total+=transfer.getProgress();
publishProgress(""+(int)((total*100)/transfer.getFileSize()));
Log.i("transfere file", "sending file status "
+ transfer.getStatus() + "progress: "
+ transfer.getProgress());
if (transfer.getStatus() == org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error) {
Log.i("transfere file", "Errorrr isss: "
+ transfer.getError()+transfer.getPeer());
transfer.cancel();
break;
}
}
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("transfere file", "sending file done");
return null;
}
#Override
protected void onProgressUpdate(final String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view =inflater.inflate(R.layout.user_chat_send_chat, null);
ProgressBar p_Bar = (ProgressBar)view.findViewById(R.id.progress_bar_image);
p_Bar.setProgress(Integer.parseInt(values[0]));
customAdapter1.notifyDataSetChanged();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
The progress Bar is the view of the custom list view, I want to update it at the run time.
Thanks
You're inflating the ProgressBar within the onProgress callback. This is absolutely wrong. The ProgressBar should to be added to the view before your AsyncTask starts (inflate and add) and then turn it to be visibile in your AsyncTask constructor. You should also store a reference to the ProgressBar in the AsyncTask (or somehow else in scope by non-static inner class).
In the end your AsyncTask should be looking like this (assuming the ProgressBar is already attached to the view):
class SendPhotoToFriend extends AsyncTask<String, String, String> {
String receiver,path = "";
ProgressBar progress;
public SendPhotoToFriend(String path, String receiver, ProgressBar progress) {
this.path = path;
this.receiver = receiver;
this.progress = progress;
this.progress.setVisibility(View.Visible);
}
#Override
protected String doInBackground(String... arg0) {
// You're application logic...
// ...
publishProgress((int)((total*100)/transfer.getFileSize()));
// ...
}
#Override
protected void onProgressUpdate(final Integer... values) {
this.progress.setProgress(values[0]);
}
}
Also you don't need to (and shouldn't) call adapter.notifiyDataSetChanged() in your onProgres-Callback.
I suppose each list item view has a progress bar, if that is the case, you can use getView to get the view for that position, and then call:
View view = customAdapter1.getView(position, convertView, parent);
ProgressBar p_Bar = (ProgressBar)view.findViewById(R.id.progress_bar_image);
p_Bar.setProgress(Integer.parseInt(values[0]));
No need to call customAdapter1.notifyDataSetChanged();

unfotunatly the application stopped [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
detail of list item in another screen
When I select an item I want the application to navigate to the second activity and take a value of selected item and the related link to the TextView which exists in the second activity. The code should work but when I run it the emulator gives me a message saying "Unfortunately the application stopped". I don't know what to do to make it work?
public class LastActivity extends ListActivity {
/** Called when the activity is first created. */
static List<String> links;
List<String> names;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String link=links.get(position);
Intent intent = new Intent(getApplicationContext(),Details.class);
intent.putExtra("name",names.get(position));
intent.putExtra("url",link);
Log.e("n",names.get(position)+"."+ link );
startActivity(intent);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
links=new ArrayList<String>();
names=new ArrayList<String>();
try{
URL url=new URL(webservice);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("Name")) {
if (insideItem)
names.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("url")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
setListAdapter(adapter);
}
private InputStream getInputStream(URL url) {
// TODO Auto-generated method stub
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
//second class or acticvites
public class Details extends LastActivity{
LastActivity last=new LastActivity();
TextView tv;
TextView url;
String read;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
tv=(TextView) findViewById(R.id.text);
url=(TextView) findViewById(R.id.link);
Intent intent=getIntent();
// receiving data
String name = intent.getStringExtra("name");
String path=intent.getStringExtra("links");
Log.e("Second Screen", name + "." + path);
tv.setText(name);
url.setText(path);
}
I think the problem is with passing putExtra values in the intents. Check your first Activity, you have used the key as "url", but in the details Activity you are using "links" as the key. So you are getting null Pointer Exception. Change it properly.
intent.putExtra("name",names.get(position));
intent.putExtra("url",link);
in Details Activity,
String name = intent.getStringExtra("name");
String path=intent.getStringExtra("url");
instead of,
String path=intent.getStringExtra("links");
In your First Activity you have exntended ListActivty, try to replace it with Activity alone.
Or change your ListView id to #android:list in your xml file.
For more info, look at this question , "Stopped Unexpectedly" tried 10000 times to fix
And also check this for more idea,
Your content must have a ListView whose id attribute is 'android.R.id.list

View ProgressBar on Gallery Intent

I'm using these codes to view an image from my application:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(imgFile), "image/*");
startActivity(intent);
I have no problem viewing the picture but when the size is a little bit larger, the intent keeps blank until the image is ready to load and show.
My question is, how can I show a ProgressBar, or in more advanced way, show a temporary image, before the real image get shown?
Thanks for the answer.
Try Asynctask as shown here:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code of UI operation
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}
Also refer to this link: Fetch data from server and refresh UI when data is fetched?:)

Categories

Resources