unable to dismiss progress bar in dialogfragment - android

I have a dialog fragment which consists of an AsyncTask class. I am able to show a progress bar inside the dialogfragment. But unable to stop it after some time. Is there any way?
class GetStatsFromUrl extends AsyncTask<String, String, String> {
//ProgressDialogFragment pf;
ProgressBar p = null;
String info, status;
JSONObject json, json1, json2;
/*String totalquestions, notanswered,
correctanswered, wronganswered;*/
String totalquestions, notanswered,
correctanswered, wronganswered;
#SuppressLint("InlinedApi")
#Override
protected void onPreExecute() {
super.onPreExecute();
//p = new ProgressDialog(getActivity());
//p.setMessage("Loading..");
//p.setIndeterminate(true);
// p.setCancelable(false);
//p.show();
p=new ProgressBar(getActivity());
// p.setVisibility(View.VISIBLE);
//p = (ProgressBar) rootView.findViewById(R.id.loading_spinner);
//p.setVisibility(View.VISIBLE);
// p.setMax(3000 -1);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// try {
String url1 = "http://smarteach.com/questions/questions.svc/Learner_Qbank_Stats_Today/val1="
+ learnerid
+ "/val2="
+ courseid
+ "/val3="
+ session_id + "";
System.out.println("Stats from URL : " + url1);
ServiceHandler sh = new ServiceHandler();
jsonstring = sh.makeServiceCall(url1, ServiceHandler.GET);
System.out.println("Response: " + jsonstring);
if (jsonstring != null && jsonstring.length() > 0) {
try {
JSONObject questionsObject = new JSONObject(jsonstring);
JSONArray questionsArray = questionsObject
.getJSONArray("Table");
if (questionsArray != null && questionsArray.length() > 0) {
for (int i = 0; i < questionsArray.length(); i++) {
JSONObject innerQuestionObject = (JSONObject) questionsArray
.get(i);
String count = innerQuestionObject.getString("Count");
String result = innerQuestionObject.getString("Result");
if (result.equalsIgnoreCase("R")) {
correctanswered = count;
} else if (result.equalsIgnoreCase("Total Questions")) {
totalquestions = count;
} else if(result.equalsIgnoreCase("W")){
// notanswered = count;
wronganswered = count;
}
/* if(result.equalsIgnoreCase("W")){
wronganswered = count;
}*/
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getActivity(), "Please try after some time",
Toast.LENGTH_LONG).show();
}
return url1;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//p.dismiss();
// TODO Auto-generated method stub
System.out.println("In onpostexecute status");
// p.setVisibility(View.GONE);
tvbookmarkcount.setText(totalquestions);
//tvquesunattempted.setText(notanswered);
tvcorrectanswered.setText(correctanswered);
tvwronganswered.setText(wronganswered);
}
}

try below code:-
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
p.dismiss();
}
you must call dismiss when your task is complete (onPostExecute).

Related

Issues while using AsyncTask in Android Studion for Two URLs

I have two URLs to fetch JSON Data.
String HttpJSonURL = "https:/.......quiz.php"
String HttpJsonCatQuizURL="https://.....catquiz.php"
Now I am calling the following methods
SaveButtonInSQLite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SQLiteDataBaseBuild();
SQLiteTableQuizBuild();
SQLiteTableCatQuizBuild();
DeletePreviousData();
new StoreJSonDataInQuiz(MainActivity.this).execute();
new StoreJSonDataInCatQuiz(MainActivity.this).execute();
}
});
And the methods are defined as
private class StoreJSonDataInQuiz extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public StoreJSonDataInQuiz(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("LOADING Quiz Data");
progressDialog.setMessage("Please Wait");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpJSonURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
Integer catid = jsonObject.getInt("catid");
Integer id=jsonObject.getInt("_id");
String question=jsonObject.getString("question");
String answer = jsonObject.getString("answer");
String opta=jsonObject.getString("opta");
String optb=jsonObject.getString("optb");
String optc=jsonObject.getString("optc");
String optd=jsonObject.getString("optd");
String SQLiteDataBaseQueryHolder = "INSERT INTO "+SQLiteHelper.TABLE_QUIZ+"" +
" (catid,_id,question,answer,opta,optb,optc,optd) VALUES( "
+catid +", "+ id +" ,'" +question+"' "+
" ,'" +answer+"' "+
" ,'" +opta +"' "+
" ,'" +optb+"' "+
" ,'" +optc+"' "+
" ,'" +optd +"' "+
");";
sqLiteDatabase.execSQL(SQLiteDataBaseQueryHolder);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
sqLiteDatabase.close();
progressDialog.dismiss();
Toast.makeText(MainActivity.this,"Load Done", Toast.LENGTH_LONG).show();
}
}
private class StoreJSonDataInCatQuiz extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public StoreJSonDataInCatQuiz(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("LOADING CATQUIZ DATA");
progressDialog.setMessage("Please Wait");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpJsonCatQuizURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
Integer id=jsonObject.getInt("_id");
String quizno=jsonObject.getString("quizno");
String SQLiteDataBaseQueryHolder = "INSERT INTO "+SQLiteHelper.TABLE_CATQUIZ+"" +
" VALUES( "
+ id +" ,'" +quizno+"'); ";
sqLiteDatabase.execSQL(SQLiteDataBaseQueryHolder);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// sqLiteDatabase.close();
progressDialog.dismiss();
Toast.makeText(MainActivity.this,"Load Done", Toast.LENGTH_LONG).show();
}
}
When I write
new StoreJSonDataInQuiz(MainActivity.this).execute();
OR
new StoreJSonDataInCatQuiz(MainActivity.this).execute();
individually, it fetches data correctly.
But when both lines are executed in sequence then its not doing the job and JSON data not fetched from the 2nd URL.
Please help

Showing ProgressBar on parsing and downloading json result

In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}

Add Update and Delete Item from Listview on Server Response Dynamically

Hi I don't know asking proper question or not but i want to develop Like Comment on Facebook post, Update comment and Delete Comment.
When i will add comment it will send request to server and it will give response with new values to fill in listadapter and that change may appear on my listview after click on enter or add button, and on delete it will send request to server and in response fill my listAdapter. and change may appear on my listview without refreshing listview. how can i perform this operation .
Thank You in Adavance.
Here is my Class.
public class CommmentActivity extends Activity{
DatabaseHandler db = new DatabaseHandler(this);
List<CommentListInfo> list_CommentInfo = new ArrayList<CommentListInfo>();
List<String> SuggetionList;
AutoCompleteTextView aCompletView;
EditText etComment;
String strComment;
ArrayAdapter<String> mentionList;
ListCommentAdapter commentAdapter;
ImageView IvAddComment;
ListView CommentList;
SessionCreator m_session;
boolean m = false;
boolean mBuzy;
int FirstPosition;
int ItemCounted;
int CurrentScrollState;
int TotalItemCount;
String UserId;
String VidoId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.commentvideo_main);
SuggetionList = new ArrayList<String>();
String Curl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo";
Intent data = getIntent();
UserId = data.getStringExtra("userId");
VidoId = data.getStringExtra("videoId");
init();
String strfriendsSyncDate = m_session.getfriendsSyncDate();
Log.d("mData", strfriendsSyncDate);
new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,Curl,"1");
commentAdapter = new ListCommentAdapter(getApplicationContext(), list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:{
commentAdapter.notifyDataSetChanged();
//ManipulateVisibleView(view);
break;
}
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
{
mBuzy = true;
break;
}
case OnScrollListener.SCROLL_STATE_FLING:{
mBuzy = true;
break;
}
default:
break;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
FirstPosition = firstVisibleItem;
ItemCounted = visibleItemCount;
TotalItemCount = totalItemCount;
int LastPosition = view.getLastVisiblePosition();
Log.d("First Position", ""+FirstPosition);
Log.d("ItemCountes",""+ItemCounted);
Log.d("totalItemCount",""+TotalItemCount);
Log.d("LastPosition",""+LastPosition);
if(visibleItemCount!=0 && ((firstVisibleItem+visibleItemCount)>=(totalItemCount))){
Log.d("mCalled", "call");
}
isScrollCompleted();
}
});
IvAddComment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
strComment = etComment.getText().toString();
etComment.getText().clear();
String strUrl = GlobalMethod.TokenGenerator() + "&action=addCommentsVideo";
new CommentsDetail().execute(UserId,VidoId,strComment,strUrl,"0");
commentAdapter.notifyDataSetChanged();
}
});
}
private void isScrollCompleted(){
if(this.ItemCounted >0 && this.CurrentScrollState == OnScrollListener.SCROLL_STATE_IDLE){
Log.d("ItemCounted",""+ItemCounted);
Log.d("CurrentScrollState",""+CurrentScrollState);
}
}
private void init() {
// TODO Auto-generated method stub
m_session = new SessionCreator(getApplicationContext());
etComment = (EditText)findViewById(R.id.etComments);
CommentList = (ListView)findViewById(R.id.lvLatestComments);
IvAddComment = (ImageView)findViewById(R.id.addComment);
}
public class CommentsDetail extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ServiceHandler serviceClient;
String mJsonString;
try{
String userId = (String)params[0];
String vId = (String)params[1];
if(params[4].equals("0")){
String comment = (String)params[2];
String strUrl = (String)params[3];
List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();
paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
paramsNameValuePairs.add(new BasicNameValuePair("commentText", comment));
serviceClient = new ServiceHandler();
mJsonString = serviceClient.makeServiceCall(strUrl,
ServiceHandler.POST, paramsNameValuePairs);
Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
}else{
String syncdate = (String)params[2];
String strUrl = (String)params[3];
List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();
paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
paramsNameValuePairs.add(new BasicNameValuePair("friendsSyncDate", syncdate));
serviceClient = new ServiceHandler();
mJsonString = serviceClient.makeServiceCall(strUrl,
ServiceHandler.POST, paramsNameValuePairs);
Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
}
Log.d("Response Json-----------------------",mJsonString );
return mJsonString;
}catch (Exception e) {
e.getStackTrace();
}
return null;
}
#SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
if (result != null) {
JSONObject responsJsonObj = new JSONObject(result);
JSONObject jsonObj = (JSONObject) responsJsonObj
.optJSONObject("data");
try {
String str = jsonObj.getString("error");
if ( str != null || str.length() != 0) {
// error
//Toast.makeText(NewsfeedActivity.this, jsonObj.getString("error"),Toast.LENGTH_LONG).show();
return;
}
} catch (JSONException je) {
Log.d("jex ------>", "" + je.getMessage());
try {
String str = jsonObj.getString("message");
Log.d("message=", "" + str);
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("comments")) {
JSONArray colArray = jsonObj.getJSONArray("comments");
Log.d("Colunm Array", ""+colArray);
int nComments = colArray.length();
Log.d("# comments", "" + nComments);
for(int i=0; i<nComments; i++){
JSONObject obj = colArray.getJSONObject(i);
Gson Comments = new Gson();
String strComments = Comments.toJson(obj);
Log.d("# obj=", "" + obj.toString());
CommentListInfo cmtInfo = new CommentListInfo();
cmtInfo.c_userId = obj.getString("userId");
cmtInfo.c_name = obj.getString("name");
cmtInfo.DateAdded = obj.getString("dateAdded");
cmtInfo.CommentId = obj.getString("commentId");
cmtInfo.CommentText = obj.getString("text");
cmtInfo.ImageUrl = obj.getString("imageLink");
list_CommentInfo.add(cmtInfo);
}
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("addPosition")) {
Log.d("# obj=", "" + jsonObj.toString());
Log.d("Add Position", jsonObj.getString("addPosition"));
}
}
//
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("friendsSyncDate")) {
Log.d("# friendsDeleted", "" + jsonObj);
Log.d("# obj=", "" + jsonObj.toString());
String myString = m_session.getfriendsSyncDate();
Log.d("myString", myString);
m_session.putfriendsSyncDate(jsonObj.getString("friendsSyncDate"));
Log.d("Sync Date "," "+jsonObj.getString("friendsSyncDate"));
}
}
} catch (JSONException je2) {
je2.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Here is my Adapter Class.
public class ListCommentAdapter extends BaseAdapter{
private Context mContext;
private List<CommentListInfo> CommentsInfo;
private LayoutInflater inflater;
private String szUserId;
private String szVideoID;
private boolean mBuzy = false;
public ListCommentAdapter(Context context, List<CommentListInfo> cmtInfo) {
// TODO Auto-generated constructor stub
mContext = context;
CommentsInfo = cmtInfo;
AppData mmap = (AppData)this.mContext.getApplicationContext();
szUserId = mmap.getUserId();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return CommentsInfo.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return CommentsInfo.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
CommentListInfo c = CommentsInfo.get(position);
try{
Log.i("nUserId", c.c_userId);
Log.i("nName", c.c_name);
Log.i("nCommentId", c.CommentId);
Log.i("nCommnet", c.CommentText);
Log.i("nImageUrl",c.ImageUrl);
}catch(Exception e){
Log.e("Erore is",""+e);
}
try{
if(inflater==null){
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null){
convertView = inflater.inflate(R.layout.comment_list_item, null);
holder.ciProfileImage = (CircleImageView)convertView.findViewById(R.id.civCFLeftPic);
holder.tvComments = (TextView)convertView.findViewById(R.id.tvCommentbox);
holder.tvCDate = (TextView)convertView.findViewById(R.id.tvCfNotifyDate);
holder.tvName = (TextView)convertView.findViewById(R.id.tvCommentName);
convertView.setTag(holder);
}else{
holder = (Holder)convertView.getTag();
}
if(!mBuzy){
RemoteImageLoader task = new RemoteImageLoader();
task.setImageView(holder.ciProfileImage);
task.execute(c.ImageUrl);
Log.d("ImagerUrl", c.ImageUrl);
if(c.ImageUrl!=null){
Picasso.with(mContext)
.load(R.drawable.world1)
.placeholder(R.drawable.world1)
.error(R.drawable.world1)
.into(holder.ciProfileImage);
}else{
Picasso.with(mContext)
.load(R.drawable.world1)
.placeholder(R.drawable.world1)
.error(R.drawable.world1)
.into(holder.ciProfileImage);
}
holder.tvComments.setText(c.CommentText);
holder.tvCDate.setText(c.DateAdded);
holder.tvName.setText(c.c_name);
holder.tvComments.setTag(null);
}else{
holder.tvComments.setText("Loading...");
holder.tvComments.setTag(this);
}
return convertView;
}catch(Exception e){
System.out.println("Error IS :- "+ e);
}
return convertView;
}
private static class Holder{
private TextView tvName,tvComments,tvCDate;
private CircleImageView ciProfileImage;
}
}
You might have solved this already but I was working on a different app in Java and came across something similar. Mine was a bit simpler because I am using a local database but ~same thing. In your CommmentActivity's onCreate method pull out the commentAdapter declaration and the CommentList.setOnScrollListener and put them in their own method. Then call your newly defined commentAdapter method in onCreate and after you parse through the response.
Something like this
public void myAdaperMethod(Context context, List<CommentListInfo> list_CommentInfo){
commentAdapter = new ListCommentAdapter(this, list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener(){...}
}
onCreate{
myAdapterMethod(...);
}
post{...}
get{myAdapterMethod(...);}
Hope that helps.
You just need to re-bind your control after the listadapter has the new dataset.
CommentList.DataBind();

android - autocomplete text view is not updating

I try to update the autocomplete textview data from the web service based text typed in the textbox. It's working fine but i put the progressbar at the time of web service call because it will take some time in this case autocomplete text view is not showing the drop down menu. I guess autocomplete textview is dissmissed at the time of progressbar dissmissed. How should we put the progress bar in this case.
Code
class GetFundNames extends AsyncTask {
ProgressDialog progress = new ProgressDialog(BasicAutoText.this);
#Override
protected void onPreExecute() {
Log.d("TAG", "onPreExecute()");
progress.setMessage("Please wait...");
progress.setCanceledOnTouchOutside(false);
progress.show();
}
#Override
// three dots is java for an array of strings
protected String doInBackground(Void... args) {
try {
response = getNames(strKeyword);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
;
return response;
}
// then our post
#Override
protected void onPostExecute(String response) {
if(progress.isShowing())
{
progress.dismiss();
}
if (ETF_Constants.registerResponsevalue == 200) {
JSONArray arObjects;
try {
arObjects = new JSONArray(response);
arProducts = new ArrayList<ProductData>();
arProducts.clear();
for (int i = 0; i < arObjects.length(); i++) {
JSONObject jOb = arObjects.getJSONObject(i);
ProductData pd = new ProductData();
int fundId = jOb.getInt("fundId");
String con = "" + fundId;
String fundName = jOb.getString("fundName");
String priceAndDate = jOb.getString("priceAndDate");
String recentGain = jOb.getString("recentGain");
String recentGrowth = jOb.getString("recentGrowth");
String tickerName = jOb.getString("tickerName");
pd.fundId = con;
pd.fundName = fundName;
pd.priceAndDate = priceAndDate;
pd.recentGain = recentGain;
pd.recentGrowth = recentGrowth;
pd.tickerName = tickerName;
arProducts.add(pd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// autocomplete
adapter = new ArrayAdapter<String>(BasicAutoText.this,
R.layout.advancelist);
adapter.setNotifyOnChange(true);
AUTO_View.setAdapter(adapter);
System.out.println("adapter" + adapter);
for (int i = 0; i < arProducts.size(); i++) {
adapter.add(arProducts.get(i).fundName);
System.out.println("Fund Name:"
+ arProducts.get(i).fundName);
}
System.out.println("arProducts count:" + arProducts.size());
System.out.println("adapter count:" + adapter.getCount());
adapter.notifyDataSetChanged();
}
}
}

I'm not able to highlight the text in a webview of speaking text in android

I am using a webview for rendering an epub and I am able to implement text to speech functionality, but i am unable to highlight the text!
I tried:
public class Epub extends Activity implements OnInitListener, OnUtteranceCompletedListener {
ProgressDialog pDialog;
WebView webview;
String line, line1 = "", finalstr = "";
int i = 0;
Book book;
String linez;
String abspath="file://android_asset/Images/";
private TextToSpeech mTts;
String htmlTextStr;
private int MY_DATA_CHECK_CODE = 0;
private HashMap<String, String> params = new HashMap<String, String>();
private int uttCount = 0;
StringTokenizer st;
private int lastUtterance = -1;
ArrayList <String> words = new ArrayList<String> ();
ArrayList <String> Swords = new ArrayList<String> ();
String utteranceId;
HashMap<String, String> lastSpokenWord = new HashMap<String, String>();
String s;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Load().execute();
mTts = new TextToSpeech(this, this);
Button mBtnSpeak = (Button) findViewById(R.id.btn);
webview = (WebView) findViewById(R.id.tv);
mBtnSpeak.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doSpeak(htmlTextStr);
}
});
}
class Load extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Epub.this);
pDialog.setMessage("Loading Epub...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
AssetManager assetManager = getAssets();
try {
Intent j = getIntent();
final String pos= j.getExtras().getString("product");
InputStream epubInputStream = assetManager.open(pos+".epub");
book = (new EpubReader()).readEpub(epubInputStream);
//coverImage =BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
// Log.i("epublib", "Coverimage is " + coverImage.getWidth() + " by " + coverImage.getHeight() + " pixels");
// DownloadResource("file:///android_asset/");
} catch (IOException e) {
Log.e("epublib", e.getMessage());
}
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
//tv.setText(Integer.toString(count));
StringBuilder string = new StringBuilder();
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
System.err.println("res media"+res.getMediaType());
htmlTextStr = Html.fromHtml(linez).toString();
Log.e("Html content.",htmlTextStr);
}
} catch (IOException e) {e.printStackTrace();}
//do something with stream
} catch (IOException e) {
e.printStackTrace();
}
}
webview.getSettings().setAllowFileAccess(true);
//System.err.println("qaz"+hr);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("file:///android_asset/", linez, "application/xhtml+xml", "UTF-8", null);
return null;
}
protected void onPostExecute(String file_url)
{
pDialog.dismiss();
}
}
public void doSpeak(String htmlTextStr) {
st = new StringTokenizer(htmlTextStr,".");
while (st.hasMoreTokens()) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,String.valueOf(uttCount++));
mTts.speak(st.nextToken(), TextToSpeech.QUEUE_ADD, params);
words.add(htmlTextStr);
}
String arr[] = htmlTextStr.split(",");
for(int i = 0; i < arr.length; i++){
System.out.println("arr["+i+"] = " + arr[i].trim());
s=arr[i].trim();
Swords.add(s);
runOnUiThread(new Runnable() {
public void run() {
webview.findAll(s);
System.err.println(" b - - >"+s);
webview.setSelected(true);
webview.findNext(true);
}
});
}
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR
if (status == TextToSpeech.SUCCESS) {
mTts.setOnUtteranceCompletedListener(this);
int result = mTts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
// Lanuage data is missing or the language is not supported.
Log.e("404","Language is not available.");
}
} else {
// Initialization failed.
Log.e("404", "Could not initialize TextToSpeech.");
// May be its not installed so we prompt it to be installed
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
installIntent.setAction(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
startActivity(installIntent);
}
}
#Override
public void onPause()
{
super.onPause();
if( mTts != null)
mTts.stop();
}
#Override
public void onDestroy() {
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
mTts.stop();
super.onDestroy();
}
#Override
public void onUtteranceCompleted(String utteranceId) {
// TODO Auto-generated method stub
Log.i("xsw",utteranceId);
lastUtterance = Integer.parseInt(utteranceId);
// createThread(s);
}
}
Could anybody help me out?
The below code is not working:
webview.findall("string");
webview.setSelected(true);
webview.findNext(true);

Categories

Resources