I know the following is probably simple, but I can't seem to get it to work. It compile and runs, but doesn't load any URL I throw at it. I have Internet set in permisions, even checked to make sure it was running in some other code.
package com.richardmather.autoaccidentattorney;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
public class FindHospitalFragment extends Fragment {
public FindHospitalFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_hospital, container, false);
final WebView webView = (WebView) rootView.findViewById(R.id.webView);
String searchURL = "http://www.stackoverflow.com";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("searchURL");
return rootView;
}
}
Here is the XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</LinearLayout>
I know it's something simple I'm missing.
EDIT: Took out the quotation marks, now it's loading the URL in Google Chrome....
The problem probably is the line webView.loadURL("searchURL");.
By doing that it actually tries to load the URL searchURL and not the URL http://www.stackoverflow.com you saved in the variable searchURL.
So just remove the "s:
webView.loadURL(searchURL); // searchURL = "http://www.stackoverflow.com"
Edit:
To not launch chrome, simply add the following line:
webview.setWebViewClient(new WebViewClient());
Also see this question for details.
Related
Following my previous post where I asked about implementing parceable objects, the solution I got was to use setRetainInstance(true); method.
#CommonsWare provided me a sample which I modified as follows:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="387dp"
android:layout_height="103dp"
android:text="New Text"
android:id="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
RotationFragmentDemo.java
package com.rotationfragment;
import android.app.Activity;
import android.os.Bundle;
public class RotationFragmentDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This check returns 'null' for the first time when there are no fragments
if (getFragmentManager().findFragmentById(android.R.id.content) == null) {
getFragmentManager().beginTransaction().add(android.R.id.content, new RotationFragment()).commit();
}
}
}
RotationFragment.java
package com.rotationfragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class RotationFragment extends Fragment implements
View.OnClickListener {
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
// This should help to retain fragment
setRetainInstance(true);
View result=inflater.inflate(R.layout.activity_main, parent, false);
result.findViewById(R.id.button).setOnClickListener(this);
textView = (TextView)result.findViewById(R.id.textView);
return(result);
}
#Override
public void onClick(View v) {
textView.setText("Hello.");
}
}
Upon rotation the text in TextView is not restored.
I know some of you would suggest using parceable writeString parceable method to fix this simple example but I want to know why is the Fragment not retained here using setRetainInstance(true)?
And I don't need to retain a string but Socket, Thread and Activity as in previous post.
See the answer, "onRetainInstance saves the Fragment object, but I still have to rebuild UI in onCreateView", So you have to restore the state of your views manually
I have read many questions here about tabs in a fragment, and did everything described here: https://developer.android.com/reference/android/support/v4/app/FragmentTabHost.html
i got no error and the app doesn't crash or something, but the fragment is just empty. The JobFragment class is a simple fragment with just one label, but it isn't displayed.
here is my java code:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AutoFragment extends Fragment{
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment_auto);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
JobFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
JobFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
JobFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
JobFragment.class, null);
return mTabHost;
}
#Override
public void onDestroyView() {
super.onDestroyView();
mTabHost = null;
}
}
and here is my layout xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
Try changing this line to:
mTabHost.setup(getActivity(), getSupportFragmentManager(), R.layout.fragment_auto);
I am not able to understand why i am getting an error here.The error is spinner1 cannot be resolved.Plz help me out fast.I am new to java and android development so explain accordingly.
This is my java code
package com.example.dailyexpenses;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class GamesFragment extends Fragment {
String[] Languages = { "Select a Language", "C# Language", "HTML Language",
"XML Language", "PHP Language" };
// Declaring the Integer Array with resourse Id's of Images for the Spinners
Integer[] images = { 0, R.drawable.icon, R.drawable.petrol,
R.drawable.books, R.drawable.recharge};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_games, container, false);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
return rootView;
}
}
This is fragment_games.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="choose from the categories below"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:drawSelectorOnTop="true"
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="#string/select">
</Spinner>
</RelativeLayout>
You need to call
rootView.findViewById
since android does not yet to know where to search.
For more explanation:
Probably (not to judge ofc) you are familiar to call findViewById in the method onCreate of an Activity, but before that you did call setContentView. After setting the content by setContentView android knows where to search for the id when you call findViewById. That is for the case when you are using activity. On the other hand, with fragments it is a different case. You won't be setting the content by setContentView, instead you have to prepare a view and return it on onCreateView and let the android set the content as it wishes. Be careful, on lines you are calling findViewById above there, you haven't return the view yet, so android does not know where to search as you call findViewById. So you have to make your searches not on not-set-yet-content, but on the rootView you are just about to return. So above the code is the solution to this well described problem.
I am trying to navigate from one fragment to another. These two fragments are 100% different, there is no ViewPager or something like that to connect them. Here is the code.
fragment_view1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/firstView">
<TextView
android:id="#+id/viewOneText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="182dp"
android:text="First View"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/viewOneBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/viewOneText"
android:layout_below="#+id/viewOneText"
android:layout_marginTop="17dp"
android:text="Click Here" />
<include layout = "#layout/drop_down"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_alignParentBottom="true"/>
<FrameLayout
android:id="#+id/fragment_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
custom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/customFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="174dp"
android:text="Custom Fragment"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
FirstView.java (uses fragment_view1.xml)
package com.example.fragmenttest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class FirstView extends DropDownMenu
{
private TextView firstText;
private Button btn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_view1,container,false);
firstText = (TextView)view.findViewById(R.id.viewOneText);
btn = (Button)view.findViewById(R.id.viewOneBtn);
btn.setOnClickListener(new ButtonEvent());
return view;
}
private class ButtonEvent implements OnClickListener
{
#Override
public void onClick(View v)
{
// Create new fragment and transaction
Fragment newFragment = new CustomView();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_view, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
CustomView.java (uses custom_view.xml)
package com.example.fragmenttest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class CustomView extends Fragment
{
private TextView secondText;
private Button secondViewBtn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.custom_view,container,false);
return view;
}
}
In FirstView.java, when I click on the button, I need to move to the Fragment CustomView. But instead moving, it simply replaces everything in CustomView on top of FirstView. Below images will explain it better.
FirstView alone
CustomView alone
When the button is FirstView clicked
Why it is happening like this?
You are trying to replace firstView with the new fragment, but firstView is not a fragment, its' a RelativeLayout.
You cannot replace a fragment defined statically in the layout file. You can only replace fragments that you added dynamically via a FragmentTransaction.
None of your Layout contains fragment in layout.
<fragment
android:id="#+id/fragment1"
android:layout_width="march_parent"
android:layout_height="match_parent"></fragment>
A new Fragment will replace an existing Fragment that was previously added to the container.
Take look on this.
If you need to replace one fragment with another then fallow undermentioned :
TalkDetail fragment = new TalkDetail();
// TalkDetail is name of fragment which you need to put while replacing older one.
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("cat", m_ArrayList.get(arg2).cat);
bundle.putString("header_title", "Talk");
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle); ((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
Here's your BaseContainerFragment.java class that will manage a lot of stuff for you.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import app.drugs.talksooner.R;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
For more specific details find my complete post over here ..
Dynamically changing the fragments inside a fragment tab host?
In my project whenever I extend activity it works fine but as soon as I extend ListActivity it throws exception and shows file not found. Why is that? We already know that ListActivity itself extends the Activity class. The application must run fine.
Here's the java file:
package com.android.feedGrabber;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.sun.cnpi.rss.elements.Item;
import com.sun.cnpi.rss.elements.Rss;
import com.sun.cnpi.rss.parser.RssParser;
import com.sun.cnpi.rss.parser.RssParserFactory;
public class feedGrabber extends Activity {
public static Collection<Item> readRSSDocument(String url) throws Exception {
RssParser parser = RssParserFactory.createDefault();
URL feedUrl = new URL(url);
URLConnection urlc=feedUrl.openConnection();
urlc.setRequestProperty("User-Agent","");
urlc.connect();
Rss rss = parser.parse(urlc.getInputStream());
return rss.getChannel().getItems();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int links=0;
try
{
for(Item item : feedGrabber.readRSSDocument("http://feeds.feedburner.com/Tutorialzine")){
if(links++>3)
break;
TextView t = (TextView)findViewById(R.id.title);
t.append("Title: ");
t.append(item.getTitle().toString());
t.append("\n\n");
//System.out.println("Title: " + item.getTitle());
//System.out.println("Link: " + item.getLink());
}
}catch(Exception e)
{
//
}
}
}
If I change "extends Activity" to "extends ListActivity" it gives the exception. I need to bring this change because I want to implement it on ListView instead of TextView.
Error it throws:
debug mode gets active and it highlights under Suspended(exception RunTimeException): ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2663.
When you extend a ListActivity, it is expecting the Layout to have a ListView that has an id of "#android:id/list", if you do not have it, it will throw an exception
You layout should look something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/noresults"/>
</LinearLayout>
Without seeing your main.xml or the exception I can't be sure, but I'd suggest checking if your list has the #android:id/list identity as required.