Android ObserveableScrollView to load more (loading issue) - android

I am fetching information from the website in JSON Format and displaying that info into my app using AsynTask. The Problem is that on On First time my Progress dialog shows well and hide after loading contents into app. But When i use Scroll-view to load more then progress dialog appears and hide after loading immediately at the same time progress dialog opens again and not hiding and Scroll-View loads data one more time in the background.I want only one time to load data after each using Scroll-View to load more. Progress Dialog is not hiding and It keeps running my app. I am struck at this point.
Basically i noticed that My Scroll-View indicator collide two times on the bottom due to this scroll-View trigger two times. How can i stop it and restrict this only one time after each scrolling.
And one more thing wanna share that everything is working awesome in Froyo 2.2 and not working in 2.3 to 4.2. Kindly help me on this. Thanks in advance.
Below is my code.
package com.example.lmf;
import java.net.URLEncoder;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.lmf.ObservableScrollView.ScrollViewListener;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
public class searchClassified extends Activity implements ScrollViewListener
{
ObservableScrollView scrollView;
ProgressDialog _progressDialog;
int page_no = 1;
String k = "";
final static String URL = "http://www.lmf.com.pk/admin/json.php?YOUR URL OF JSON";
final getInternetData obj = new getInternetData();
public ImageLoader imageLoader = null;
Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_classified);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
scrollView = (ObservableScrollView) findViewById(R.id.my_scroll);
scrollView.setScrollViewListener(this);
imageLoader = new ImageLoader(this);
String s = getIntent().getExtras().getString("query")!= "" ? getIntent().getExtras().getString("query") : "";
EditText et = (EditText) findViewById(R.id.query);
et.setText(s);
k = "all="+URLEncoder.encode(s);
//showProgress(context);
new getBackgroundData().execute();
}
public void onScrollEnded(ObservableScrollView scrollView, int x, int y,
int oldx, int oldy) {
// TODO Auto-generated method stub
page_no = page_no + 1;
k = k+"&page_no="+page_no;
//showProgress(context);
getBackgroundData d1 = new getBackgroundData();
d1.execute();
if(d1.getStatus()==AsyncTask.Status.FINISHED) {
d1 = null;
_progressDialog.dismiss();
}
}
public void searchAds(View v)
{
EditText query = (EditText) findViewById(R.id.query);
String q = query.getText().toString();
if(q == "" || q == "search")
{
Dialog d = new Dialog(this);
d.setTitle("Enter Valid Search Parameter");
d.show();
}
else
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Intent i = new Intent(searchClassified.this,com.example.lmf.searchClassified.class);
i.putExtra("query", ""+q+"");
startActivity(i);
}
}
public void showProgress(Context c)
{
_progressDialog = ProgressDialog.show(
c,
"Please wait",
"Performing task..."
);
}
public void hideProgress()
{
_progressDialog.dismiss();
}
//////////// Async Class
private class getBackgroundData extends AsyncTask<Void, Integer, JSONArray>
{
protected void onPreExecute()
{
_progressDialog = new ProgressDialog(context);
_progressDialog.setMessage("Loading...");
_progressDialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
try
{
JSONArray array = obj.getDATA(k,URL);
return array;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray array)
{
LinearLayout sv = (LinearLayout) findViewById(R.id.data);
try
{
for (int i = 0; i <array.length(); i++) {
JSONObject row = array.getJSONObject(i);
//// TextView Creation start here /////////
TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
tv.setText(row.getString("post_title"));
tv.setTextColor(Color.BLACK);
tv.setTextSize(14);
tv.setPadding(8, 6, 0, 12);
tv.setFocusable(true);
tv.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
//// TextView Creating Ends here /////////
//// Horizontal Line Creating here /////////
View v = new View(searchClassified.this);
LinearLayout.LayoutParams viewLp = new LayoutParams(LayoutParams.MATCH_PARENT, 1);
viewLp.setMargins(0, 4, 0, 4);
v.setLayoutParams(viewLp);
v.setBackgroundColor(Color.LTGRAY);
//// Horizontal Line Creating Ends here /////////
//// Image Creating Starts from here /////////
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(3, 0, 15, 8);
lp.width = 70;
lp.height = 80;
ImageView imageView = new ImageView(searchClassified.this);
String[] parts = row.getString("post_img").split("/");
int last_index = parts.length - 1;
String image_name = "thumb_"+parts[last_index];
String str = "";
for(int j=0; j<last_index; j++)
{
str += parts[j]+"/";
}
String path = "http://www.lmf.com.pk/"+str+image_name;
imageLoader.DisplayImage(path, imageView);
//// Image Creating Ends here /////////
// Creating LinearLAyout /////////
LinearLayout l1 = new LinearLayout(searchClassified.this);
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setHapticFeedbackEnabled(true);
l1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
l1.setId(obj.convertStrtoInt(row.getString("post_id")));
l1.setHapticFeedbackEnabled(true);
l1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(searchClassified.this,com.example.lmf.adsDetail.class);
i.putExtra("id", v.getId());
startActivity(i);
}
});
l1.addView(imageView, lp);
l1.addView(tv);
sv.addView(l1);
sv.addView(v);
}
_progressDialog.hide();
_progressDialog.dismiss();
_progressDialog = null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
/////////// Ends Here
public boolean onCreateOptionsMenu(Menu menu)
{
MenuItem item = menu.add ("Quit");
item.setOnMenuItemClickListener (new OnMenuItemClickListener()
{
public boolean onMenuItemClick (MenuItem item)
{
//clearArray();
finish();
return true;
}
});
return true;
}
}

I have Solved this issue and want to share with the future readers. I made a switch and add cases now the new Scroll-View trigger can not run until the previous data will not complete loads.
Here is the final code and hope will help you friends. Thanks
package com.example.lmf;
import java.net.URLEncoder;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.lmf.ObservableScrollView.ScrollViewListener;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
public class searchClassified extends Activity implements ScrollViewListener
{
ObservableScrollView scrollView;
ProgressDialog _progressDialog;
int page_no = 1;
String k = "";
final static String URL = "Your URL HERE For Getting JSON";
final getInternetData obj = new getInternetData();
public ImageLoader imageLoader = null;
Context context = this;
int num = 1;
private static final int SPLASH_DURATION = 3000; // 3 seconds
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_classified);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
scrollView = (ObservableScrollView) findViewById(R.id.my_scroll);
scrollView.setScrollViewListener(this);
imageLoader = new ImageLoader(this);
String s = getIntent().getExtras().getString("query")!= "" ? getIntent().getExtras().getString("query") : "";
EditText et = (EditText) findViewById(R.id.query);
et.setText(s);
k = "all="+URLEncoder.encode(s);
showProgress();
new getBackgroundData().execute();
}
public void onScrollEnded(ObservableScrollView scrollView, int x, int y, int oldx, int oldy)
{
// TODO Auto-generated method stub
page_no = page_no + 1;
k = k+"&page_no="+page_no;
switch(num)
{
case 1:
showProgress();
new getBackgroundData().execute();
num = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
num = 1;
}
}, SPLASH_DURATION);
break;
case 0:
num = 0;
break;
}
}
public void searchAds(View v)
{
EditText query = (EditText) findViewById(R.id.query);
String q = query.getText().toString();
if(q == "" || q == "search")
{
Dialog d = new Dialog(this);
d.setTitle("Enter Valid Search Parameter");
d.show();
}
else
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Intent i = new Intent(searchClassified.this,com.example.lmf.searchClassified.class);
i.putExtra("query", ""+q+"");
startActivity(i);
}
}
public void showProgress()
{
_progressDialog = new ProgressDialog(context);
_progressDialog.setMessage("Loading...");
_progressDialog.show();
}
public void hideProgress()
{
_progressDialog.dismiss();
}
//////////// Async Class
private class getBackgroundData extends AsyncTask<Void, Integer, JSONArray>
{
#Override
protected JSONArray doInBackground(Void... params)
{
try
{
JSONArray array = obj.getDATA(k,URL);
return array;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray array)
{
LinearLayout sv = (LinearLayout) findViewById(R.id.data);
try
{
for (int i = 0; i <array.length(); i++) {
JSONObject row = array.getJSONObject(i);
//// TextView Creation start here /////////
TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
tv.setText(row.getString("post_title"));
tv.setTextColor(Color.BLACK);
tv.setTextSize(14);
tv.setPadding(8, 6, 0, 12);
tv.setWidth(350);
tv.setHeight(100);
tv.setFocusable(true);
LinearLayout.LayoutParams tvPar = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//tvPar.weight = 2;
tv.setLayoutParams(tvPar);
//// TextView Creating Ends here /////////
//// Horizontal Line Creating here /////////
View v = new View(searchClassified.this);
LinearLayout.LayoutParams viewLp = new LayoutParams(LayoutParams.MATCH_PARENT, 1);
viewLp.setMargins(0, 4, 0, 4);
v.setLayoutParams(viewLp);
v.setBackgroundColor(Color.LTGRAY);
//// Horizontal Line Creating Ends here /////////
//// More Detail Icon Ends /////////////////////
ImageView more_info_icon = new ImageView(searchClassified.this);
//setting image resource
more_info_icon.setImageResource(R.drawable.arrow);
//setting image position
LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//par.weight = 1;
more_info_icon.setLayoutParams(par);
more_info_icon.getLayoutParams().height = 30;
more_info_icon.getLayoutParams().width = 30;
more_info_icon.setPadding(0, 14, 0, 0);
/// More Detail Icon Ends Here /////////////////////
//// Image Creating Starts from here /////////
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,4);
lp.weight = 1;
lp.setMargins(3, 0, 15, 8);
lp.width = 70;
lp.height = 80;
ImageView imageView = new ImageView(searchClassified.this);
String[] parts = row.getString("post_img").split("/");
int last_index = parts.length - 1;
String image_name = "thumb_"+parts[last_index];
String str = "";
for(int j=0; j<last_index; j++)
{
str += parts[j]+"/";
}
String path = "http://www.lmf.com.pk/"+str+image_name;
imageLoader.DisplayImage(path, imageView);
//// Image Creating Ends here /////////
// Creating LinearLAyout /////////
final LinearLayout l1 = new LinearLayout(searchClassified.this);
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setHapticFeedbackEnabled(true);
LinearLayout.LayoutParams LParam = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LParam.weight = 4;
l1.setLayoutParams(LParam);
l1.setId(obj.convertStrtoInt(row.getString("post_id")));
l1.setHapticFeedbackEnabled(true);
l1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
l1.setBackgroundColor(Color.GREEN);
//l1.setBackgroundColor(Color.WHITE);
Intent i = new Intent(searchClassified.this,com.example.lmf.adsDetail.class);
i.putExtra("id", v.getId());
startActivity(i);
}
});
l1.addView(imageView, lp);
l1.addView(tv);
l1.addView(more_info_icon);
sv.addView(l1);
sv.addView(v);
}
hideProgress();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
/////////// Ends Here
public boolean onCreateOptionsMenu(Menu menu)
{
MenuItem item = menu.add ("Quit");
item.setOnMenuItemClickListener (new OnMenuItemClickListener()
{
public boolean onMenuItemClick (MenuItem item)
{
//clearArray();
finish();
return true;
}
});
return true;
}
}

Related

Not able to capture HTML from the browser for Android

I am trying to capture HTML code response from browser. I have created a browser and trying to capture HTML content and print in logcat.
I am getting following error message in logcat:
01-28 13:36:18.914 4079-4079/com.aseelarbazanny.myweb D/PocketMagic: onPageFinished
01-28 13:36:18.954 4079-4079/com.aseelarbazanny.myweb I/chromium: [INFO:CONSOLE(1)] "Uncaught TypeError: Object [object Object] has no method 'showHTML'", source: http://www.pocketmagic.net/ (1)
Here is the code I have done so far:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class AndroidBrowserGUI extends Activity implements View.OnClickListener {
// constants
final static String LOG_TAG = "PocketMagic";
final static int idTopLayout = Menu.FIRST + 100,
idBack = Menu.FIRST + 101,
idBotLayout = Menu.FIRST + 102,
idAddr = Menu.FIRST + 103,
idButBack = Menu.FIRST + 104,
idButFwd = Menu.FIRST + 105,
idButReload = Menu.FIRST + 106,
idButStop = Menu.FIRST + 107,
idButGo = Menu.FIRST + 108;
// interface controls
String m_szPage = "http://www.pocketmagic.net";
int m_nHTMLSize = 0;
WebView m_web;
EditText m_etAddr;
TextView m_tv;
Button m_bButBack, m_bButFwd, m_bButReload, m_bButStop, m_bButGo;
#Override
#SuppressLint("JavascriptInterface")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hide titlebar
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Create our top content holder
RelativeLayout global_panel = new RelativeLayout (this);
global_panel.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT));
global_panel.setGravity(Gravity.FILL);
global_panel.setBackgroundDrawable(getResources().getDrawable( R.drawable.back));
// +++++++++++++ TOP COMPONENT: the header
RelativeLayout ibMenu = new RelativeLayout(this);
ibMenu.setId(idTopLayout);
ibMenu.setBackgroundDrawable(getResources().getDrawable(R.drawable.line));
int ibMenuPadding = (int) 6;
ibMenu.setPadding(ibMenuPadding,ibMenuPadding,ibMenuPadding,ibMenuPadding);
RelativeLayout.LayoutParams topParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
topParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
global_panel.addView(ibMenu,topParams);
//
int nTextH = 12;
// go button
m_bButGo = new Button(this);
m_bButGo.setId(idButGo);
m_bButGo.setOnClickListener((View.OnClickListener) this);
m_bButGo.setText("Go");
m_bButGo.setTextSize(nTextH);
m_bButGo.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb5 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb5.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lpb5.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenu.addView(m_bButGo, lpb5);
// address field
m_etAddr = new EditText(this);
m_etAddr.setId(idAddr);
m_etAddr.setText(m_szPage);
nTextH = 12;
m_etAddr.setTextSize(nTextH);
m_etAddr.setTypeface(Typeface.create("arial", Typeface.NORMAL));
RelativeLayout.LayoutParams lpbEdit =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpbEdit.addRule(RelativeLayout.RIGHT_OF, idButGo);
lpbEdit.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenu.addView(m_etAddr, lpbEdit);
// +++++++++++++ BOTTOM COMPONENT: the footer
RelativeLayout ibMenuBot = new RelativeLayout(this);
ibMenuBot.setId(idBotLayout);
ibMenuBot.setBackgroundDrawable(getResources().getDrawable(R.drawable.line));
ibMenuBot.setPadding(ibMenuPadding,ibMenuPadding,ibMenuPadding,ibMenuPadding);
RelativeLayout.LayoutParams botParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
botParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
global_panel.addView(ibMenuBot,botParams);
m_bButBack = new Button(this);
m_bButBack.setId(idButBack);
m_bButBack.setOnClickListener((View.OnClickListener) this);
m_bButBack.setText("Back");
m_bButBack.setTextSize(nTextH);
m_bButBack.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb1 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lpb1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenuBot.addView(m_bButBack, lpb1);
// fwd button
m_bButFwd = new Button(this);
m_bButFwd.setId(idButFwd);
m_bButFwd.setOnClickListener((View.OnClickListener) this);
m_bButFwd.setText("Fwd");
m_bButFwd.setTextSize(nTextH);
m_bButFwd.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb2 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb2.addRule(RelativeLayout.RIGHT_OF, idButBack);
lpb2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenuBot.addView(m_bButFwd, lpb2);
// reload button
m_bButReload = new Button(this);
m_bButReload.setId(idButReload);
m_bButReload.setOnClickListener((View.OnClickListener) this);
m_bButReload.setText("Rld");
m_bButReload.setTextSize(nTextH);
m_bButReload.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb3 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb3.addRule(RelativeLayout.RIGHT_OF, idButFwd);
lpb3.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenuBot.addView(m_bButReload, lpb3);
// stop button
m_bButStop = new Button(this);
m_bButStop.setId(idButStop);
m_bButStop.setOnClickListener((View.OnClickListener) this);
m_bButStop.setText("Stop");
m_bButStop.setTextSize(nTextH);
m_bButStop.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb4 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb4.addRule(RelativeLayout.RIGHT_OF, idButReload);
lpb4.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenuBot.addView(m_bButStop, lpb4);
// status
m_tv = new TextView(this);
m_tv.setText("Status");
m_tv.setTextColor(Color.rgb(255,255,255));
m_tv.setTextSize(nTextH);
m_tv.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpcTV = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpcTV.addRule(RelativeLayout.RIGHT_OF, idButStop);
lpcTV.addRule(RelativeLayout.CENTER_VERTICAL);
ibMenuBot.addView(m_tv, lpcTV);
// +++++++++++++ MIDDLE COMPONENT: only a webview control
m_web = new WebView(this);
m_web.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT));
RelativeLayout.LayoutParams midParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
midParams.addRule(RelativeLayout.ABOVE,ibMenuBot.getId());
midParams.addRule(RelativeLayout.BELOW,ibMenu.getId());
global_panel.addView(m_web,midParams );
// Configure our webview object
m_web.getSettings().setJavaScriptEnabled(true);
m_web.setWebViewClient(new MyWebViewClient());
// set starting page
if (m_szPage != null) m_web.loadUrl(m_szPage);
// set java script used to get the HTML code
m_web.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");
// Interface READY
setContentView(global_panel);
}
// Used with Webview, to get the HTML code
class JavaScriptInterface{
public void showHTML(String html) {
m_nHTMLSize = 0;
if (html !=null) {
//int i = html.lastIndexOf(""); //search for something in the text
m_nHTMLSize = html.length();
Log.d(LOG_TAG, "HTML content is: "+html+"\nSize:"+m_nHTMLSize+" bytes");
}
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(LOG_TAG, "onPageStarted");
m_tv.setText("Loading page...");
//stop button is enabled only when pages are loading
m_bButStop.setEnabled(true);
}
#Override
public void onPageFinished(WebView view, String url) {
Log.d(LOG_TAG, "onPageFinished");
m_tv.setText("Ready");
//stop button is disabled when pages are already loaded
m_bButStop.setEnabled(false);
// This call inject JavaScript into the page which just finished loading.
m_web.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
// adjust prev/next buttons, only if history is available
m_bButBack.setEnabled(m_web.canGoBack());
m_bButFwd.setEnabled(m_web.canGoForward());
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
int id = arg0.getId();
// If cancel is pressed, close our app
if (id == idBack) finish();
if (id == idButGo) {
m_szPage = m_etAddr.getText().toString();
Log.d(LOG_TAG, "Go for page:"+m_szPage);
if (m_szPage != null) m_web.loadUrl(m_szPage);
}
if (id == idButBack) {
Log.d(LOG_TAG, "Go back");
m_web.goBack();
}
if (id == idButFwd) {
Log.d(LOG_TAG, "Go forward");
m_web.goForward();
}
if (id == idButReload) {
Log.d(LOG_TAG, "Reload page");
m_web.reload();
}
if (id == idButStop) {
Log.d(LOG_TAG, "Stop loading page");
m_web.stopLoading();
}
}
}
Starting from API level JELLY_BEAN_MR1 and above, only methods explicitly marked with the #JavascriptInterface annotation are available to the Javascript code.
You just need to add this above your showHTML method e.g:
class JavaScriptInterface{
#JavascriptInterface
public void showHTML(String html) {
m_nHTMLSize = 0;
if (html !=null) {
//int i = html.lastIndexOf(""); //search for something in the text
m_nHTMLSize = html.length();
Log.d(LOG_TAG, "HTML content is: "+html+"\nSize:"+m_nHTMLSize+" bytes");
}
}
}
Also need to remove window from you JS call:
m_web.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
to
m_web.loadUrl("javascript:HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");

Convert to AnsyncTask Android

I am new to Android development, I am working on a App and I want to convert my below mentioned code to AnsyncTask. Because it is showing me Run-time error that I am doing too much work on UI thread. Please help me to convert it to AnsyncTask.
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for(int i=1; i<=strLength; i++){
if(i == 2){
dash = dash+Character.toString(randomStr.charAt(1));
} else if (i == 5){
dash = dash+ Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter (getApplicationContext(),android.R.layout.simple_list_item_1,array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String finalDisplayVal = displayVal;
int count = 0;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if(randomStr.contains(itemValue)){ // If selected alphabets exists in string
for(int k=0; k<strLength; k++){
if(Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)){
int charPos = randomStr.indexOf(itemValue);
while(charPos >= 0){
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4-count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if(count > 3) {
Toast.makeText(PlayActivity.this, "You Loose, Value is: "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount(){
if(randomStr.equalsIgnoreCase(finalDisplayVal)){
Toast.makeText(PlayActivity.this, "Hurray!!! You WIN... It's "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
});
}
}
AsyncTask Code;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity1 extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
int count = 0;
String randomStr;
String finalDisplayVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for (int i = 1; i <= strLength; i++) {
if (i == 2) {
dash = dash + Character.toString(randomStr.charAt(1));
} else if (i == 5) {
dash = dash + Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String finalDisplayVal = displayVal;
runner.execute(finalDisplayVal);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if (randomStr.contains(itemValue)) { // If selected alphabets exists in string
for (int k = 0; k < strLength; k++) {
if (Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)) {
int charPos = randomStr.indexOf(itemValue);
while (charPos >= 0) {
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4 - count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
});
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if (count > 3) {
Toast.makeText(PlayActivity1.this, "You Loose, Value is: " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount() {
if (randomStr.equalsIgnoreCase(finalDisplayVal)) {
Toast.makeText(PlayActivity1.this, "Hurray!!! You WIN... It's " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
private class AsyncTaskRunner extends AsyncTask<String, String, ProgressDialog> {
#Override
protected ProgressDialog doInBackground(String... params) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity1.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
try {
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
}catch (Exception e){
e.printStackTrace();
}
return mProgressDialog;
}
}
}

Android Async Task freeze the UI

Hi I have an Activity which user open upon click on a TAB. Actually I have a ViewGroup and Tabactivity as Main Activity. on the first tab I have three activity.
Now in an activity I have a list view (custom) populating on Oncreate and a ViewFlipper (only adding view) in Onresume using AsyncTask.
In that asynctask in Pre Execute if I add code for loader it gives error. Also If I do not show the loader the screen is freezing until the Async task finished.
I actually want to load the list view first and then in background run the async task with a loader. Also does not want to freeze the screen.
Here Is My Acivity
package thai.phrasi.ctech.com.phrasi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class WordActivity extends ActionBarActivity {
categories category_obj;
word word_obj;
wordDB wordDb;
WordAdapter adapter;
MediaPlayer mPlayer;
boolean doubleBackToExitPressedOnce = false;
public static ViewFlipper viewFlipper;
public View view;
private static ProgressDialog pleaseWaitDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word);
viewFlipper = new ViewFlipper(this);
viewFlipper.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
TextView txt = (TextView) findViewById(R.id.phraseListHeading);
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
String categoryName = getIntent().getExtras().getString("categoryName").toUpperCase();
wordDb = new wordDB(getApplicationContext());
getAllWords();
//asyncLoadWordList task2 = new asyncLoadWordList(getApplicationContext());
//task2.execute();
txt.setTypeface(font);
txt.setText(categoryName);
ListView wordListView;
wordListView = (ListView)findViewById(R.id.list_view_word);
wordListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = parent.getItemAtPosition(position);
word_obj = (word) o;
if(Integer.valueOf(word_obj.getCategoryId())>=0) {
Intent myIntent = new Intent(WordActivity.this, WordDetailsActivity.class);
myIntent.putExtra("word_obj", word_obj);
myIntent.putExtra("position",position);
myIntent.putExtra("currentClickedId", word_obj.getCsvWordId().toString());
myIntent.putExtra("favouriteFlag",0);
myIntent.putExtra("searchFlag",0);
myIntent.putExtra("searchString", "");
WordActivity.this.startActivity(myIntent);
}
}
});
ImageView backButton = (ImageView) findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent backIntent = new Intent(WordActivity.this, CategoryActivity.class);
View vw = FirstGroup.group.getLocalActivityManager().startActivity("CategoryActivity", backIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
FirstGroup.group.replaceView(vw);
viewFlipper.removeAllViews();
System.runFinalization();
Runtime.getRuntime().gc();
System.gc();
}
});
}
#Override
protected void onPause() {
super.onPause(); // Don't forget this line
stop();
}
public void stop(){
mPlayer=adapter.getMPlayerInstace();
if(mPlayer!=null){
mPlayer.stop();
mPlayer.release();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_word, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onResume(){
super.onResume();
new Thread(new Runnable() {
public void run(){
//All your heavy stuff here!!!
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
if(viewFlipper.getChildCount() == 0) {
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
}).start();
}
public void getAllWords(){
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5), row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
adapter = new WordAdapter(WordActivity.this, words);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
//Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Double tap back button to exit.");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
public class asyncLoadWordList extends AsyncTask<ArrayList<word>, Void, ArrayList<word>>{
private Context mContext;
public asyncLoadWordList(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
/* if (pleaseWaitDialog == null)
pleaseWaitDialog= ProgressDialog.show(WordActivity.this,
"PLEASE WAIT",
"Getting results...",
false);
*/
}
#Override
protected ArrayList<word> doInBackground(ArrayList<word>... params) {
wordDb = new wordDB(mContext);
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
return words;
}
protected void onPostExecute(ArrayList<word> result) {
adapter = new WordAdapter(WordActivity.this, result);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
if (pleaseWaitDialog != null) {
pleaseWaitDialog.dismiss();
pleaseWaitDialog = null;
}
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
public class asyncFlipperView extends AsyncTask<String, Void, String[]> {
String categoryId;
private Context mContext;
wordDB wordDb;
Cursor row;
JSONObject json;
View view;
//private ProgressDialog dialog = new ProgressDialog(WordActivity.this);
public asyncFlipperView(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
}
#Override
protected String[] doInBackground(String... params) {
categoryId = params[0];
json = new JSONObject();
/*do application level task*/
GlobalState state = ((GlobalState) mContext);
state.doAction();
/*Ends*/
wordDb = new wordDB(mContext);
row = wordDb.selectWordList(categoryId);
Log.d("Tag: search result", row.getString(2).toString());
return new String[]{categoryId};
}
protected void onPostExecute(String[] result) {
categoryId = result[0];
ImageView phraseImage = null;
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
row.moveToFirst();
while (!row.isAfterLast()) {
/*phrase Image*/
Integer fileNameLength = row.getString(5).toString().length();
String fileName = row.getString(5).toString();
String imageFile = fileName.substring(0, fileNameLength - 4);
//viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.word_details_flipper_view, null);
TextView tv = (TextView) view.findViewById(R.id.text_english);
tv.setTypeface(font);
tv.setText(row.getString(2).toString());
String picName = row.getString(6).toString();
picName = picName.replace(".png", "");
Uri url1 = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + picName);
ImageView backgroundImage = (ImageView) view.findViewById(R.id.backgroundImage);
Picasso.with(mContext).load(url1).fit().centerCrop().into(backgroundImage);
TextView tvTranslated = (TextView) view.findViewById(R.id.translated_phrase);
tvTranslated.setTypeface(font);
tvTranslated.setText(row.getString(3).toString());
TextView pronounce = (TextView) view.findViewById(R.id.pronounce);
pronounce.setTypeface(font);
pronounce.setText(row.getString(4).toString());
phraseImage = (ImageView) view.findViewById(R.id.phrase_image);
Uri url = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + imageFile);
Picasso.with(mContext).load(url).resize(576, 888).into(phraseImage);
view.setTag(R.string.csvId, row.getString(0).toString());
viewFlipper.addView(view);
row.moveToNext();
}
row.close();
}
private Context getDialogContext() {
Context context;
if (getParent() != null) context = getParent();
else context = WordActivity.this;
return context;
}
}
}

get value from edit text within a loop

I have a question, as I can get all the data that has been inserted into the edit text? the edit text is on a loop, I need a way to get those values ​​and work with them, try using an array but I get errors. could help me? any idea? Help!
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText count = (EditText) findViewById(R.id.count);
final Button generate = (Button) findViewById(R.id.generate);
final LinearLayout container = (LinearLayout) findViewById(R.id.container);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberOfControlsToGenerate = 0;
try {
numberOfControlsToGenerate = Integer.parseInt(count.getText().toString().trim());
} catch (NumberFormatException e) {
Log.e(TAG, e.getMessage(), e);
}
if (numberOfControlsToGenerate > 0) {
if (container.getChildCount() > 0) {
container.removeAllViews();
}
for (int counter = 0; counter < numberOfControlsToGenerate; counter++) {
addEditText(container);
}
}
}
});
}
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
container.addView(editTextToAdd);
}
}
You can create multiple edittext by using array.
public class MainActivity extends Activity{
EditText[] sample_et;
int numberOfControlsToGenerate = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
LinearLayout root_layout = (LinearLayout)findViewById(R.id.root);
sample_et = new EditText[numberOfControlsToGenerate];
//numberOfControlsToGenerate is decleres statically you can get the count from edit text
for(int i = 0; i < count; i++ ){
sample_et[i] = new EditText(this);
root_layout.addView(sample_et[i]);
}
}
}
Add setTag when you create dynamic EditText
add line in addEditText(LinearLayout container) method
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
editTextToAdd.setTag(editTextToAdd); //Add this Line
container.addView(editTextToAdd);
}
Write code onClick listener on any Button
getvalue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < container.getChildCount(); i++) {
if(container.getChildAt(i) instanceof EditText) {
EditText et = (EditText) container.getChildAt(i).getTag();
if(et != null) {
Log.i("<Tag Name>", et.getText().toString());
}
}
}
}
});

EditText Customization

In my application , I am dynamically generating a linearlayout that contains an edittext and some Buttons .
I want that when the user presser the 'enter' on the keyboard of device the keyboard should hide
I tried it by setting the input type of the edittext , But by this when the user presses "enter" it moves onto another edittext .
How can i do that??
package com.integrated.mpr;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class Page1 extends Activity implements OnClickListener{
static String partname;
int pos = StaticError.n;
int ns= StaticError.ns;
String s = StaticError.s;
int[][] id = new int[pos][6];
int submit ;
double timedataa[] = {0,0,0,0,0};
double timedatab[] = {0,0,0,0,0};
double timedatac[] = {0,0,0,0,0};
double timedata[] = {0,0,0,0,0};
double rawdataa[] = new double[22050];
double rawdatab[] = new double[22050];
double rawdatac[] = new double[22050];
double rawdata[] = new double[22050];
FeatureExtract fe = new FeatureExtract();
WavToDat wtd = new WavToDat();
int i;
int a=0;
int b=0;
int c=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int p =0;
Log.d("value of ", ""+pos);
//Creating Different ids for the elements for different layouts
for(int i =0;i<pos;i++){
for(int j =0;j<6;j++){
id[i][j] = p;
p++;
}
}
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
int resid = getResources().getIdentifier("background", "drawable", getPackageName());
ll.setBackgroundResource(resid);
Button ins = new Button(this);
ins.setText("Instructions");
ins.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
ins.setGravity(Gravity.RIGHT);
ins.setId(5000);
ins.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
Context mContext = Page1.this;
Dialog dialog = new Dialog(mContext);
dialog.setTitle("Instructions");
dialog.setContentView(R.layout.instructiondialog);
dialog.show();
}
});
ins.setTextColor(Color.BLUE);
ins.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
ins.setTypeface(Typeface.SERIF);
ll.addView(ins);
for(i=0;i<pos;i++){
LinearLayout llay = new LinearLayout(this);
llay.setOrientation(LinearLayout.VERTICAL);
llay.setId(id[i][5]);
//EDIT TEXT
EditText et = new EditText(this);
et.setId(id[i][0]);
et.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
et.setTypeface(Typeface.SERIF);
LinearLayout lhor = new LinearLayout(this);
lhor.setOrientation(LinearLayout.HORIZONTAL);
lhor.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
lhor.setWeightSum(90);
Button starta = new Button(this);
starta.setText("Record 1");
starta.setId(id[i][1]);
starta.setOnClickListener(this);
Button startb = new Button(this);
startb.setText("Record 2");
startb.setId(id[i][2]);
startb.setOnClickListener(this);
Button startc = new Button(this);
startc.setText("Record 3");
startc.setId(id[i][3]);
startc.setOnClickListener(this);
lhor.addView(starta);
lhor.addView(startb);
lhor.addView(startc);
Button stop = new Button(this);
stop.setText("Submit");
stop.setId(id[i][4]);
stop.setOnClickListener(this);
TextView tv1 = new TextView(this);
tv1.setVisibility(llay.INVISIBLE);
llay.addView(tv);
llay.addView(et);
llay.addView(lhor);
llay.addView(stop);
llay.addView(tv1);
ll.addView(llay);
}
sv.addView(ll);
this.setContentView(sv);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Try the following:
final EditText et = new EditText(this);
et.setId(id[i][0]);
et.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
et.setTypeface(Typeface.SERIF);
et.setOnKeyListener(new View.OnKeyListener()
{
#Override
public boolean onKey(View editView, int keyCode, KeyEvent event)
{
Context mContext = Page1.this;
if( keyCode == KeyEvent.KEYCODE_ENTER ){
et.clearFocus();
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et.getWindowToken(),0);
return true;
}
return false;
}
})

Categories

Resources