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>');");
Related
i need to achieve horizontal scrolling of pages while swiping
i have loaded data in the order of json ,inside the textview and webview
i have used viewpager for achieving that operation
im receiving the error as shown in log cat
i have used removeView() method ,error is showing up again
Kindly Help me to solve this
Thanks in advance
My Code
package singlearticle;
import com.yslabs.yourstory.R;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
#SuppressLint("SetJavaScriptEnabled")
public class SingleArticle extends Activity {
String t = single.title;
String p = single.permalink;
String f = single.featured_img;
String a = single.author;
String d = single.date;
String articleComment = "article url" + p;
private WebView web1, fbCommentview;
ConnectionDetector checkConnection;
Boolean isInternetPresent = false;
ViewPager viewPage;
MyPagerAdapter mypageAdapter;
private ProgressDialog pDialog;
#SuppressWarnings("deprecation")
#SuppressLint({ "InflateParams", "SetJavaScriptEnabled", "HandlerLeak",
"NewApi" })
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.singlearticle);
viewPage = (ViewPager) findViewById(R.id.myviewpager);
mypageAdapter = new MyPagerAdapter();
viewPage.setAdapter(mypageAdapter);
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#f8f8f8")));
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ActionBar mActionBar = getActionBar();
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(SingleArticle.this);
View mCustomView = mInflater
.inflate(R.layout.customactionbar,null);
TextView mTitleTextView = (TextView) mCustomView
.findViewById(R.id.title_text);
Typeface fontt = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
mTitleTextView.setTypeface(fontt);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setLogo(R.drawable.backicon);
// getActionBar().setIcon(
// new
// ColorDrawable(getResources().getColor(android.R.color.transparent)));
pDialog = new ProgressDialog(SingleArticle.this);
pDialog.setMessage("Loading...");
pDialog.show();
pDialog.setCancelable(false);
final Handler h = new Handler() {
public void handleMessage(Message message) {
pDialog.dismiss();
}
};
h.sendMessageDelayed(new Message(), 500);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main2, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_refresh:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, t + "\n" + p);
sendIntent.setType("text/plain");
startActivity(sendIntent);
return true;
case android.R.id.home:
onBackPressed();
web1.loadUrl("");
web1.stopLoading();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
// progressBar.setVisibility(View.GONE);
}
}
// To handle "Back" key press event for WebView to go back to previous
// screen.
#SuppressWarnings("static-access")
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == event.KEYCODE_BACK) {
web1.loadUrl("");
web1.stopLoading();
finish();
}
return super.onKeyDown(keyCode, event);
}
private class MyPagerAdapter extends PagerAdapter {
int articleCount = 5;
#Override
public int getCount() {
// returns article count
return articleCount;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
// assigns object to view
return view == ((LinearLayout)obj);
}
#SuppressLint("NewApi")
#Override
public Object instantiateItem(ViewGroup container, int position) {
d = d.substring(0, d.length() - 3);
String c = single.content;
c = c.replace("src=\"//", "src=\"https://");
final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(c, ALLOWED_URI_CHARS);
String htmldata = "<!DOCTYPE html><html><style = text/css> img{width:100%!important;height:auto!important;} iframe{width:100sp;max-height:100sp;}a { color:#3366CC; text-decoration: none; } </style> <body style = 'line-height:25px;'>"
+ c + "</body></html>";
TextView titleTxt = (TextView) findViewById(R.id.singletitle);
titleTxt.setText(t);
// tt = titleTxt.getText().toString();
Typeface font = Typeface.createFromAsset(getAssets(),
"Helvetica Neue UltraLight.ttf");
Typeface font22 = Typeface.createFromAsset(getAssets(),
"helvetica-neue-regular-1361522098.ttf");
titleTxt.setTypeface(font);
titleTxt.setTypeface(font22);
titleTxt.setTypeface(null, Typeface.BOLD);
TextView authorTxt = (TextView) findViewById(R.id.singleauthor);
authorTxt.setText(a);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
authorTxt.setTypeface(font1);
TextView dateTxt = (TextView) findViewById(R.id.singledate);
dateTxt.setText(d);
Typeface font2 = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
dateTxt.setTypeface(font2);
TextView permalinkTxt = (TextView) findViewById(R.id.singleperlink);
permalinkTxt.setText(p);
permalinkTxt.setVisibility(View.GONE);
// pp = permalinkTxt.getText().toString();
// datep.setVisibility(View.GONE);
web1 = (WebView) findViewById(R.id.webView2);
web1.setWebViewClient(new myWebClient());
web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
web1.getSettings().setJavaScriptEnabled(true);
// web1.getSettings().setJavaScriptEnabled(true);
// web1.setInitialScale(65);
web1.getSettings().setDefaultFontSize(18);
web1.setWebChromeClient(new WebChromeClient());
web1.getSettings().setPluginState(PluginState.ON_DEMAND);
// web1.loadUrl("http://dev.skyle.co/fbSDK.php?data="+urlEncoded);
web1.loadData(htmldata, "text/html; charset=utf-8", null);
web1.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent in = new Intent(SingleArticle.this, webview.class);
webclass.webdata = url.toString();
startActivity(in);
return true;
}
});
fbCommentview = (WebView) findViewById(R.id.fbCommentview);
/*
* to check internet and show/hide facebook part
*/
checkConnection = new ConnectionDetector(getApplicationContext());
isInternetPresent = checkConnection.isConnectingToInternet();
if (isInternetPresent) {
// Toast.makeText(getApplicationContext(),"Internet Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.VISIBLE);
} else {
// Toast.makeText(getApplicationContext(),"Internet Not Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.GONE);
}
fbCommentview.setWebViewClient(new myWebClient());
fbCommentview.getSettings()
.setJavaScriptCanOpenWindowsAutomatically(true);
fbCommentview.getSettings().setJavaScriptEnabled(true);
fbCommentview.getSettings().setDefaultFontSize(18);
fbCommentview.setWebChromeClient(new WebChromeClient());
fbCommentview.getSettings().setPluginState(PluginState.ON_DEMAND);
fbCommentview.loadUrl(articleComment);
System.out.println("Title" + t);
System.out.println("Content" +c);
LinearLayout layout = new LinearLayout(SingleArticle.this);
layout.setOrientation(LinearLayout.VERTICAL);
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
layout.setLayoutParams(layoutParams);
layout.addView(titleTxt);
layout.addView(dateTxt);
layout.addView(web1);
layout.addView(fbCommentview);
container.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
}
The Error in LOGCAT
here
TextView titleTxt = (TextView) findViewById(R.id.singletitle);
TextView authorTxt = (TextView) findViewById(R.id.singleauthor);
TextView permalinkTxt = (TextView) findViewById(R.id.singleperlink);
web1 = (WebView) findViewById(R.id.webView2);
fbCommentview = (WebView) findViewById(R.id.fbCommentview);
these all the views contains one parent already.. because of that reason your unable to add it again..if you want to add to the layout here. you have to create those textview like this, instead of getting from xml.
TextView textView = new TextView(MainActivity.this);
and then add to the layout.
Replace below method and try:
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater;
View view = inflater.inflate(R.layout.singlearticle, container, false);
d = d.substring(0, d.length() - 3);
String c = single.content;
c = c.replace("src=\"//", "src=\"https://");
final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(c, ALLOWED_URI_CHARS);
String htmldata = "<!DOCTYPE html><html><style = text/css> img{width:100%!important;height:auto!important;} iframe{width:100sp;max-height:100sp;}a { color:#3366CC; text-decoration: none; } </style> <body style = 'line-height:25px;'>"
+ c + "</body></html>";
TextView titleTxt = (TextView)view.findViewById(R.id.singletitle);
titleTxt.setText(t);
// tt = titleTxt.getText().toString();
Typeface font = Typeface.createFromAsset(getAssets(),
"Helvetica Neue UltraLight.ttf");
Typeface font22 = Typeface.createFromAsset(getAssets(),
"helvetica-neue-regular-1361522098.ttf");
titleTxt.setTypeface(font);
titleTxt.setTypeface(font22);
titleTxt.setTypeface(null, Typeface.BOLD);
TextView authorTxt = (TextView)view.findViewById(R.id.singleauthor);
authorTxt.setText(a);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
authorTxt.setTypeface(font1);
TextView dateTxt = (TextView)view.findViewById(R.id.singledate);
dateTxt.setText(d);
Typeface font2 = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
dateTxt.setTypeface(font2);
TextView permalinkTxt = (TextView)view.findViewById(R.id.singleperlink);
permalinkTxt.setText(p);
permalinkTxt.setVisibility(View.GONE);
// pp = permalinkTxt.getText().toString();
// datep.setVisibility(View.GONE);
web1 = (WebView)view.findViewById(R.id.webView2);
web1.setWebViewClient(new myWebClient());
web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
web1.getSettings().setJavaScriptEnabled(true);
// web1.getSettings().setJavaScriptEnabled(true);
// web1.setInitialScale(65);
web1.getSettings().setDefaultFontSize(18);
web1.setWebChromeClient(new WebChromeClient());
web1.getSettings().setPluginState(PluginState.ON_DEMAND);
// web1.loadUrl("http://dev.skyle.co/fbSDK.php?data="+urlEncoded);
web1.loadData(htmldata, "text/html; charset=utf-8", null);
web1.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent in = new Intent(SingleArticle.this, webview.class);
webclass.webdata = url.toString();
startActivity(in);
return true;
}
});
fbCommentview = (WebView)view.findViewById(R.id.fbCommentview);
/*
* to check internet and show/hide facebook part
*/
checkConnection = new ConnectionDetector(getApplicationContext());
isInternetPresent = checkConnection.isConnectingToInternet();
if (isInternetPresent) {
// Toast.makeText(getApplicationContext(),"Internet Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.VISIBLE);
} else {
// Toast.makeText(getApplicationContext(),"Internet Not Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.GONE);
}
fbCommentview.setWebViewClient(new myWebClient());
fbCommentview.getSettings()
.setJavaScriptCanOpenWindowsAutomatically(true);
fbCommentview.getSettings().setJavaScriptEnabled(true);
fbCommentview.getSettings().setDefaultFontSize(18);
fbCommentview.setWebChromeClient(new WebChromeClient());
fbCommentview.getSettings().setPluginState(PluginState.ON_DEMAND);
fbCommentview.loadUrl(articleComment);
// System.out.println("Title" + t);
// System.out.println("Content" +c);
// LinearLayout layout = new LinearLayout(SingleArticle.this);
// layout.setOrientation(LinearLayout.VERTICAL);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// layout.setLayoutParams(layoutParams);
// layout.addView(titleTxt);
// layout.addView(dateTxt);
// layout.addView(web1);
// layout.addView(fbCommentview);
// container.addView(layout);
return view;
}
I have a fragment with a relative layout - which is correctly displayed.
Now I try to add a custom view with canvas - where I can dynamically draw on. But the onDraw-method of the custom view is not called if I call the drawConnectionLine method from the custom View. If I do not call the drawConnectionLine method it works.
I tried to call the drawConnectionLine in the onResume-method after the view is created but it does not help...
How can I dynamically draw on the custom view after initialization without a NullPointerException(because of the onDraw not being executed)?
Here is my fragment-code(FragmentPlan.java):
package de.tucais.svm.youplan;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import android.app.Activity;
import android.app.Fragment;
import android.content.ContentValues;
import android.graphics.Canvas;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class FragmentPlan extends Fragment
{
// Define logging variables
private static final String LOGCAT = "YP-FragmentPlan";
private static final boolean D = true; // control debug-output
Activity parentActivity;
LibSVM svm = null;
DatabaseController db;
Controller controller = null;
DrawView drawView = null;
//Canvas drawCanvas = null;
int firstTv_margin_top, firstTv_margin_left, firstTv_margin_right, firstTv_margin_bottom;
int tv_margin_top, tv_margin_left, tv_margin_right, tv_margin_bottom;
RelativeLayout planLayout = null;
List<TextView> taskElements = new ArrayList<TextView>();
public FragmentPlan()
{
}
public void onResume()
{
super.onResume();
computeResult();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_plan, container, false);
controller = new Controller((MainActivity)getActivity());
planLayout = (RelativeLayout)view.findViewById(R.id.relativeLayout_plan);
// Translate the margin-values from dp to pixel
firstTv_margin_left = getResources().getDimensionPixelSize(R.dimen.plan_firstTv_margin_left);
firstTv_margin_top = getResources().getDimensionPixelSize(R.dimen.plan_firstTv_margin_top);
firstTv_margin_right = getResources().getDimensionPixelSize(R.dimen.plan_firstTv_margin_right);
firstTv_margin_bottom = getResources().getDimensionPixelSize(R.dimen.plan_firstTv_margin_bottom);
tv_margin_left = getResources().getDimensionPixelSize(R.dimen.plan_tv_margin_left);
tv_margin_top = getResources().getDimensionPixelSize(R.dimen.plan_tv_margin_top);
tv_margin_right = getResources().getDimensionPixelSize(R.dimen.plan_tv_margin_right);
tv_margin_bottom = getResources().getDimensionPixelSize(R.dimen.plan_tv_margin_bottom);
// Create the DrawView and append it to the RelativeLayout
drawView = new DrawView((MainActivity)getActivity());
RelativeLayout.LayoutParams drawViewParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
drawView.setLayoutParams(drawViewParams);
drawView.setId(View.generateViewId());
planLayout.addView(drawView);
//sendViewToBack(drawView);
if(D) Log.i(LOGCAT,"drawCanvas created...");
if(D) Log.i(LOGCAT,"onCreateView finished...");
return view;
}
private void computeResult()
{
List<ContentValues> result = controller.computeSequence();
//displayResult(result.get(0));
for(int i=0; i < result.size(); i++)
{
displayResultElement(result.get(i));
if(i > 0)
{
if(D) Log.i(LOGCAT,"tried to draw connection for " + i + " time...");
if(D) Log.i(LOGCAT,"DrawCanvas is null: " + drawView.isCanvasNull()); //-> returns true
drawView.drawConnectionLine(taskElements, i); //-> this call causes the error
if(D) Log.i(LOGCAT,"succesfully drawed connection nr" + i + "...");
}
}
}
private void displayResultElement(ContentValues resultElement)
{
// Create a new element
TextView newElement = new TextView((MainActivity)getActivity());
newElement.setId(View.generateViewId());
newElement.setBackground(getResources().getDrawable(R.drawable.shape_circle));
// Fill the new Element with its content
Set<Entry<String, Object>> s = resultElement.valueSet();
Iterator<Entry<String, Object>> itr = s.iterator();
Map.Entry<String, Object> me = (Map.Entry<String, Object>)itr.next();
newElement.append(me.getKey().toString()+": " + me.getValue().toString());
while(itr.hasNext())
{
me = (Map.Entry<String, Object>)itr.next();
newElement.append("\n"+me.getKey().toString()+": " + me.getValue().toString());
}
// After filling the new element with content append it to its parent view element
planLayout.addView(newElement);
// add the element to the list
taskElements.add(newElement);
// Position the new element on the screen
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)newElement.getLayoutParams();
// if there is more than the current element in the list position relative to the predecessor
if(taskElements.size() > 1)
{
params.addRule(RelativeLayout.BELOW, taskElements.get(taskElements.size()-2).getId());
params.addRule(RelativeLayout.ALIGN_LEFT, taskElements.get(taskElements.size()-2).getId());
params.setMargins(tv_margin_left, tv_margin_top, tv_margin_right, tv_margin_bottom);
}
else
{
params.setMargins(firstTv_margin_left, firstTv_margin_top, firstTv_margin_right, firstTv_margin_bottom);
}
newElement.setLayoutParams(params);
}
private static void sendViewToBack(final View v)
{
final ViewGroup parent = (ViewGroup)v.getParent();
if (parent != null)
{
parent.removeView(v);
parent.addView(v, 0);
}
}
}
This is my xml-file for the relativeLayout(fragment_plan.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relativeLayout_plan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="2dp"
tools:context=".MainActivity" >
</RelativeLayout>
Here is my CustomView(DrawView.java):
package de.tucais.svm.youplan;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class DrawView extends View
{
// Define logging variables
private static final String LOGCAT = "YP-DrawView";
private static final boolean D = true; // control debug-output
private Canvas drawCanvas = null;
public DrawView(final Context context)
{
super(context);
if(D) Log.i(LOGCAT,"DrawView constructor called... ");
}
#Override
protected void onMeasure(int w, int h)
{
if(D) Log.d(LOGCAT,"onMeasure with w= " + w + " and h= " + h + " called...");
setMeasuredDimension(w, h);
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if(D) Log.i(LOGCAT,"onDraw called... ");
this.drawCanvas = canvas;
if(D) Log.d(LOGCAT,"drawCanvas still empty? " + (this.drawCanvas == null));
}
/*
* Method which draws a connection line between two graphical elements on the screen
* #param {List<TextView>} taskElements - a list of all TextView-elements
* #param {int} nr - the number of the destination element
*/
public void drawConnectionLine(List<TextView> taskElements, int nr)
{
if(D) Log.i(LOGCAT,"drawConnectionLine called... ");
TextView currentElement = taskElements.get(nr);
TextView prevElement = null;
try
{
prevElement = taskElements.get(nr-1);
}
catch(Exception e)
{
Log.e(LOGCAT, "No predacessor!!!");
}
int startX = computeCenter(prevElement);
int startY = prevElement.getBottom();
int stopX = computeCenter(currentElement);
int stopY = currentElement.getTop();
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
this.drawCanvas.drawLine(startX, startY, stopX, stopY, paint); //-> this.drawCanvas == null => Why???
}
private int computeCenter(View element)
{
int result = 0;
if(element != null)
{
int right = element.getRight();
result = right - (element.getWidth()/2);
}
return result;
}
public void emptyCanvas()
{
// Clear the canvas
this.drawCanvas.drawColor(Color.TRANSPARENT);
}
public boolean isCanvasNull()
{
return this.drawCanvas == null;
}
}
It would be very nice, if someone can explain me, why the onDraw-method of the DrawView is not called when calling the drawConnectionLine method- the reason for a NullPointerException in the FragmentPlan.java line 95.
Thanks in advance!!!
Yeah it seems like system assumes the view width and height to be zero and thus did not called on onDraw(). You can override the onMeasure(int, int) method in View class to specify the width and height of your view.
Link:
Custom onDraw() method not called
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;
}
}
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;
}
})
How can I get the id of an element that has been clicked, if this element is found in a scrollView? In my case I have 4 photos (ImageViews) and if I click on one of them, I want to get its id (already set with ImageView.setId(int) ). Here is my code:
package scroll.s;
import android.app.Activity;
import android.os.Bundle;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ScrollsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int layoutId = 0;
RelativeLayout main = new RelativeLayout(this);
RelativeLayout.LayoutParams mainParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
main.setId(layoutId);
layoutId++;
TextView past = new TextView (this);
RelativeLayout.LayoutParams pastParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
past.setId(layoutId);
layoutId++;
past.setText("Past: ");
pastParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
main.addView(past, pastParams);
final HorizontalScrollView hsv = new HorizontalScrollView(this);
hsv.setId(layoutId);
layoutId++;
hsv.setHorizontalScrollBarEnabled(false);
mainParams.addRule(RelativeLayout.BELOW, 1);
main.addView(hsv, mainParams);
final RelativeLayout relative1 = new RelativeLayout(this);
relative1.setId(layoutId);
layoutId++;
hsv.addView(relative1);
for (int i=0; i<4; i++) {
ImageView current = new ImageView(this);
current.setBackgroundDrawable(getResources().getDrawable(R.drawable.example));
current.setId(layoutId);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, (layoutId-1) );
params.leftMargin=10;
relative1.addView(current, params);
layoutId++;
}
for (int i=0; i<4; i++) {
TextView currentText = new TextView(this);
currentText.setText("random text");
currentText.setId(layoutId);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, (layoutId-4) );
params.addRule(RelativeLayout.ALIGN_LEFT, (layoutId-4) );
params.topMargin=5;
relative1.addView(currentText, params);
layoutId++;
}
this.setContentView(main);
}
}
Here is what I achieve with this code :
I get the ERROR/AndroidRuntime(2258): android.content.res.Resources$NotFoundException: String resource ID #0x4
when I put the following code:
current.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), current.getId(), Toast.LENGTH_SHORT).show();
}
});
Change it to:
current.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), String.valueOf(v.getId()), Toast.LENGTH_SHORT).show();
}
});
the second parameter of the method makeText() , is a String , not an Int ( current.getId() ) , so you should convert it to a String like this :
current.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),""+v.getId(), Toast.LENGTH_SHORT).show();
}
});