Hi i have a MainActivity class where i have a listview populated by rss items. When i click on item list my app shows me an alertdialog where i can see in message box the item details. My problem is that after i show alertdialog when i close it and open a new item my app crashes giving me this error:
FATAL EXCEPTION: main.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Here my java class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView);
wv = new WebView(this);
try {
url = new URL("http://www.unikore.it/index.php/ingegneria-informatica-home?format=feed");
} catch (MalformedURLException e) {
e.printStackTrace();
}
new ReadRssTask().execute(url);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
OptionDialog = new AlertDialog.Builder(MainActivity.this).create();
OptionDialog.setTitle(listview.getItemAtPosition(position).toString());
s = rssItems.get(position).getDescription();
if(s.contains("href=")){
s.substring(0,s.indexOf("</div>"));
wv.loadData(s, "text/html", "UTF-8");
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
OptionDialog.setView(wv);
}else {
OptionDialog.setMessage(s.replaceAll("<[^>]*>", ""));
}
OptionDialog.show();
}
});
}
i tried using OptionDialog.dismiss() method but app crashes anyway.
Thanks
move the instantiation of the WebView just before accessing the object.
s = rssItems.get(position).getDescription();
if(s.contains("href=")){
wv = new WebView(this);
wv.loadData(s, "text/html", "UTF-8");
// other code
Related
I´m new to android and i´m using the first time webview, fragment, drawer...
I have the problem that with my code after pressing fullscreen in the video my app is crashing.
And i have no idea what is going wrong...
WebViewFragmentVideos
public class WebViewFragmentVideos extends Fragment {
WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.Websitesenglish);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle(menus[position]);
//Initializing and loading url in webview
webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
webView.setWebChromeClient(new MyChromeClient());
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
return v;}
class MyChromeClient extends WebChromeClient {
String url = getArguments().getString("url");
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
Intent intent = new Intent(null, LandVideoAct.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("video", url);
startActivity(intent);
}
}
}
and
LandVideoAct
public class LandVideoAct extends Activity {
WebView webView, fullweb;
String url = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
setContentView(R.layout.landfull);
url = getIntent().getStringExtra("video") + "?fs=1";
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
webView = (WebView) findViewById(R.id.fullwebview);
if (Build.VERSION.SDK_INT < 8) {
webView.getSettings().setPluginsEnabled(true);
} else {
webView.getSettings().setPluginState(PluginState.ON);
}
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
LandVideoAct.this.finish();
}
});
webView.loadUrl(url);
}}
I hope you dudes can help me with my problem.
Thank you!!
this piece of line of code is not allowed in android.
Intent intent = new Intent(null, LandVideoAct.class);
coming to your crash problem. Its mainly because of a above line of code. When full screen of video in webview is called , its gives call to android system ie onShowCustomView(View view, CustomViewCallback callback). Where you above line of code is failing.
instead of that use activity context or application context
Intent intent = new Intent(context, LandVideoAct.class);
I am trying to pass information form one Activity to the other and while doing that I would like to have a progress dialog show. Mainly when the second activity is processing the information. I have been reading up and the proper way of doing it seems to be asynctask. Or is there another way of doing it?
Here is my code: Activity one
public class SearchActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
String query = edittext.getText().toString();
// gets the text and makes sure its a string
Intent intent = new Intent(SearchActivity.this,
DissertationActivity.class);
intent.putExtra("query1", query);
startActivity(intent);
return true;
}
return false;
}
});
final Button button = (Button) findViewById(R.id.searchButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String query = edittext.getText().toString();
// gets the text and makes sure its a string
Intent intent = new Intent(SearchActivity.this,
DissertationActivity.class);
intent.putExtra("query1", query);
startActivity(intent);
}
});
}
}
This is the Second activity:
public class DissertationActivity extends ListActivity {
/** Called when the activity is first created. */
public ArrayList<String> book_Array = new ArrayList<String>();
ArrayAdapter<String> adapter;
String href = "";
String href1 = "";
String search_Word = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
search_Word = extras.getString("query1");
adapter = new ArrayAdapter<String>(this, R.layout.list_item_1,
book_Array);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
try {
Document doc = null;
Document guestLink = null;
guestLink = Jsoup.connect("https://aulib.abdn.ac.uk:443/F").get();
Element link = guestLink.select("p > a").first();
href1 = link.attr("href");
href = href1.substring(0, href1.length() - 2); // removes -0 from
// the
// href_Array.add(href); //adds href to the array because string
// wont add to the public var.
doc = Jsoup.connect(
href + "&request=" + search_Word
+ "&find_code=WRD&adjacent=N&x=0&y=0").get();
// System.out.println(doc);
Elements headings = doc.select("td:eq(3)");
// System.out.println(headings);
for (Element heading : headings) {
// System.out.println(heading.text());
String j = heading.text();
book_Array.add(j);
}
} catch (IOException e) {
e.printStackTrace();
}
book_Array.remove(0);
adapter.notifyDataSetChanged();
book_Array.remove(1);
adapter.notifyDataSetChanged();
book_Array.remove(2);
adapter.notifyDataSetChanged();
book_Array.remove("Search");
adapter.notifyDataSetChanged();
book_Array.remove(" | ");
adapter.notifyDataSetChanged();
book_Array.remove(0);
adapter.notifyDataSetChanged();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
// Context context = getApplicationContext();
int query = position;
// String text = book_Array.get(position);
// int duration = Toast.LENGTH_SHORT;
// Toast toast = Toast.makeText(context,
// String.valueOf(position), //shows the postion in the array
// list
// duration);
// toast.show();
Intent intent = new Intent(DissertationActivity.this,
FullDetailsActivity.class);
intent.putExtra("href", href);
intent.putExtra("query1", (int) query);
intent.putExtra("search_Word", search_Word);
startActivity(intent);
}
});
}
}
I tried using:
this.pd = ProgressDialog.show(this, "Working..", "Downloading Data...",
true, false);
But that didn't work.
How would I go about, so that it displays a progress dialog in between the activities?
Thanks for your help!
Calling ProgressDialog.show will block the UI thread. So the progress dialog/bar will not show up until the method has returned. So we can create a thread for our method to run within it. This will avoid blocking the main UI Thread.
Sample code -
ProgressDialog spinnerDialog = ProgressDialog.show(
Placeholder.this, "","Your text ", true);
new Thread(new Runnable() {
public void run() {
//your method code
return;
}
}).start();
I'm trying to call different activities depending on the item the user clicks on my listview but for some reason only the first element is working.
here is the code for the listview:
options = (ListView) findViewById(R.id.lstOptions);
ArrayAdapter<String> OPTADAP= new ArrayAdapter<String>(this,R.layout.optionslayout,OPTIONS);
options.setAdapter(OPTADAP);
options.setOnItemClickListener(new OnItemClickListener(){
Intent i;
#Override
public void onItemClick(AdapterView<?> parent, final View view,int pos, long id) {
switch(pos){
case 0:
i = new Intent(view.getContext(),Posting.class);
i.putExtra("usrid", usrdata.get("id"));
i.putExtra("usrname", usrdata.get("name"));
try{
startActivity(i);
} catch(ActivityNotFoundException e) {
e.printStackTrace();
}
break;
case 1:
i = new Intent(view.getContext(),WallActivity.class);
try{
startActivity(i);
}catch(ActivityNotFoundException e){
e.printStackTrace();
}
break;
default:
Toast.makeText(view.getContext(), "default", 10).show();
}
}
}
for some reason the block of code in case 1 does not run, i tried putting the code from case 0 in case 1 and it worked, so it has to be something wrong with this block:
i = new Intent(view.getContext(),WallActivity.class);
try{
startActivity(i);
}catch(ActivityNotFoundException e){
e.printStackTrace();
}
the WallActivity is basically just a webview:
public class WallActivity extends Activity{
WebView wv;
private final String wurl = "URL HERE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wallactivity);
wv = (WebView) findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl(wurl);
}
}
When i click on item 1 the code does not run, any ideas? all the help is greatly appreciated.
Why on earth are you catching the ActivityNotFoundException? If i had to hazard a guess, it woud be that you forgot to register WallActivity in your manifest and that exception is being thrown.
In any case, if you do catch an exception, in Android, if you want to see the stack trace you should write the exception to the Log instead of e.printStackTrace()
Log.e(getClass().getName(), "OMG ERROR ! :)", e);
I m Using WebView in AlertDialog to authenticate user to twitter.
but When i click on field in webview ,android keyboard doesnt open.
here is my code that shows how i added webview in alert dialog.
i implicitly call android keyboard but it open keyboard behind alert dialog.
here is my code.
public static void webViewDialog(final String authorizationURL, final int type)
{
final boolean correctPin;
System.out.println("In webViewDialog");
container = new LinearLayout(context);
container.setOrientation(LinearLayout.VERTICAL);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(context);
webView.setMinimumWidth(200);
webView.requestFocusFromTouch();
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new TwitterWebViewClient());
webView.loadUrl(authorizationURL);
webView.setBackgroundColor(0xFFbbd7e9);
container.addView(webView);
Builder webDialog = new AlertDialog.Builder(context);
webDialog.setView(container).setTitle("Twitter Login")
.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
if (type == 0)
{
twitterPinCodeDialog();
dialog.dismiss();
}
}
}).show();
showVirtualKeyboard();
}
public static void showVirtualKeyboard()
{
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
InputMethodManager m = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if(m != null)
{
// m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
m.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);
}
}
}, 100);
}
Here is my solution to this problem:
Put a dummy edit text, and set it's visibility to GONE, and add it to a containing LinearLayout, after adding the WebView to the layout.
Example:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LinearLayout wrapper = new LinearLayout(this);
WebView webView = new WebView(this);
EditText keyboardHack = new EditText(this);
keyboardHack.setVisibility(View.GONE);
webView.loadUrl(url);
wrapper.setOrientation(LinearLayout.VERTICAL);
wrapper.addView(webView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
wrapper.addView(keyboardHack, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
builder.setView(wrapper);
builder.create().show();
Once this is done, everything should work properly, and when you select an item in the WebView, the keyboard appears as expected.
I am using a PopupWindow with a WebView inside it and experienced the same problem, but if I set focusable to true in the parent the problem goes away:
popupWindow.setFocusable(true);
Hope this helps!
I had a similar issue and solved it in this way:
I override the onCreateView() method on the dialog fragment and define all view stuff configuration for my web view.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
// do some config
// some other stuffs
loginpage.loadUrl(url);
return view;
}
On the onCreateDialog() method i just add these.
#Override
public Dialog onCreateDialog(Bundle savedInstaceState) {
Dialog dialog = super.onCreateDialog(savedInstaceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
In my case i wanted to show a dialog with no title. So due the DialogBuilder take care of creating dialog's view i decided to override the onCreateView() and just call the super.onCreateDialog() and add my window configuration.
I also suffer from this problem, I solved this problem by customizing Dialog, here is my custom dialog code, hope so this is use full for you.
TwitterDialog fb=new TwitterDialog(this);
fb.abc();
//fb.dismiss();
class TwitterDialog extends Dialog {
Context context;
String url="https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1<mpl=default<mplcache=2";
public TwitterDialog(Context context) {
super(context);
this.context=context;
}
void abc(){
LinearLayout mContent = new LinearLayout(context);
mContent.setOrientation(LinearLayout.VERTICAL);
final float scale = context.getResources().getDisplayMetrics().density;
float[] dimensions =new float[]{400.0f,500.0f};
addContentView(mContent, new FrameLayout.LayoutParams(
(int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
FrameLayout.LayoutParams FILL =
new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
WebView mWebView = new WebView(context);
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new WebClicent());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
TwitterDialog.this.show();
}
class WebClicent extends WebViewClient{
#Override
public void onLoadResource(WebView view, String url) {
System.out.println("onLoadResource "+url);
super.onLoadResource(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
System.out.println("onPageFinished "+url);
//TwitterDialog.this.dismiss();
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
System.out.println("onPageStarted "+url);
super.onPageStarted(view, url, favicon);
}
}
}//TWitterDialog
The reason your keyboard may not be showing up, is probably because you are using a device that already has a hard keyboard. ANY DEVICE WITH A PHYSICAL KEYBOARD does not need to show a soft keyboard... That is why it is not showing. Because your device or your emulator has a physical hard keyboard.
I have a simple linearlayout with a textbox a button and a listview, I'm doing some URL data getting when something is entered in the textbox and the button is pressed I want to parse the results and display in the listview.
What I can't work out is how to instatiate the listview from within my extende activity class and add it to the layout? I think I'm barking up the wrong tree !
public class HelloAndroid extends Activity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyList L;
L = new MyList();
//setContentView(L.getListView());
EditText edittext = (EditText)findViewById(R.id.editText1);
edittext.setText("");
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
EditText edittext = (EditText)findViewById(R.id.editText1);
executeHttpGet(edittext.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void executeHttpGet(String vrm) throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://xxx/vrmtest.asp?vrm="+vrm));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
Context context = getApplicationContext();
CharSequence text = page;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class MyList extends ListActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse",
"Ubuntu", "Solaris", "Android", "iPhone"};
// Create an ArrayAdapter, that will actually make the Strings above
// appear in the ListView
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
}
}
An explanation would suffice rather than code but an example would be nice.
As long as your main.xml layout file has a ListView in it, you're on the right path. Set its #+id to something arbitrary and reference it in your code with:
ListView lv = (ListView) findViewById(R.id.arbitrary_id);
You don't necessarily need a ListActivity to use a ListView. Simply parse the data that you receive back from the server, put it in an array, and use lv.setAdapter(your_array_adapter) to fill the ListView with your data.
You can go further and specify your ItemClickListener by:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
}
};
Alternatively, you can create the ListView programmatically using
ListView lv = new ListView(this);
and adding it to a view in your layout with
some_container_view_in_main.addView(lv);
Then you would set the ArrayAdapter and OnItemClickListener the same as above.
You shouldn't create an Activity object yourself. Android will do it for you. Read this article, it will help you: http://developer.android.com/guide/topics/intents/intents-filters.html
If you want to add a ListView to your layout, just add it in the layout xml file. You can't add one activity to another until parent activity extends ActivityGroup. But that's not your case.
If what you want is to add the list to your layout, then use ListView instead of ListActivity.
you can then add the list as this.addView (myList);
Please follow the example here: http://developer.android.com/resources/tutorials/views/hello-listview.html