App crash if I try to open a fragment in an activity - java

every time I try to open my fragment in my MainActivity.class my app crashs.
MainActivity.class
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_server:
Intent intent = new Intent(getApplicationContext(), AddServerFragment.class);
startActivity(intent);
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
...
public class AddServerFragment extends Fragment {
public AddServerFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.add_ip, container, false);
Button btn_back, btn_add;
final EditText server_ip, server_name;
server_ip = (EditText) findViewById(R.id.edit_server_address);
server_name = (EditText) findViewById(R.id.edit_server_name);
/* Back Button */
btn_back = (Button) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
/* Add IP Button */
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String new_server_ip = null, new_server_name = null;
ArrayList<String> server_name_list = new ArrayList<String>();
ArrayList<String> server_ip_list = new ArrayList<String>();
new_server_ip = server_ip.getText().toString();
server_ip_list.add(new_server_ip);
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
}
});
return rootView;
}
}
My errorlog only say, I have to add the Fragment in my Manifest.xml as activity. But I know, I don't have to add it there.
Errorlog
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: FATAL EXCEPTION: main
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: Process: de.kwietzorek.fulcrumwebview, PID: 18345
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: android.content.ActivityNotFoundException: Unable to find explicit activity class {de.kwietzorek.fulcrumwebview/de.kwietzorek.fulcrumwebview.MainActivity$AddServerFragment}; have you declared this activity in your AndroidManifest.xml?
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3917)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3877)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:784)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4200)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4168)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at de.kwietzorek.fulcrumwebview.MainActivity.onOptionsItemSelected(MainActivity.java:90)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.onMenuItemSelected(Activity.java:2908)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:361)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV7.onMenuItemSelected(AppCompatDelegateImplV7.java:621)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:191)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AdapterView.performItemClick(AdapterView.java:310)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsListView$PerformClick.run(AbsListView.java:3042)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsListView$3.run(AbsListView.java:3879)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Edit
My Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

Wrong with the above code:
ERROR Intent intent = new Intent(getApplicationContext(), AddServerFragment.class);
startActivity(intent);
Use the correct method for using fragment, you have used method for starting activity.
AddServerFragment is Fragment not activity.
For fragment to add in activity, you have to use the following approach:
In your activity,
XML code part in activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java Code Part in MainActivity.class:
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
// Create an instance of AddServerFragment
AddServerFragment firstFragment = new AddServerFragment();
// if there are any extras
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}

You need to add the activity declaration to your manifest file:
<activity android:name=".MainActivity" >
</activity>

You cant use intent when you want open fragment.
You can try FragmentManager.
Example:
public void getFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
if (mFragment == null) {
mFragment = fragment;
fm.beginTransaction()
.add(R.id.fragment_container, mFragment)
.commit();
}
if (mFragment != null) {
mFragment = fragment;
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
}

Related

How to access a button from in a another layout in a Fragment

i am trying to get a button from another layout in fragment.this fragment have another inflate another layout.i get a java.lang.NullPointerException. how to solve this problem?
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.add_to_cart_display, container, false);
myAdapter=new MyAdapter(getActivity());
Button remove=(Button) view.findViewById(R.id.remove_cart_items);
RecyclerView recyclerView=(RecyclerView)view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
ch=new CartHelper(getActivity());
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
rc=new RCadapter(getDataset());
recyclerView.setAdapter(rc);
return view;
}
from above pgm the remove button not in the add_cart_display xml file. it locate in another layout file. here i am accessing this button.it give the following error.
10-31 12:38:20.484 13886-13886/com.infizoom.infishopping
E/AndroidRuntime: FATAL EXCEPTION: main 10-31 12:38:20.484
13886-13886/com.infizoom.infishopping E/AndroidRuntime: Process:
com.infizoom.infishopping, PID: 13886 10-31 12:38:20.484
13886-13886/com.infizoom.infishopping E/AndroidRuntime:
java.lang.NullPointerException 10-31 12:38:20.484
13886-13886/com.infizoom.infishopping E/AndroidRuntime: at
com.infizoom.infishopping.add_cart_class.onStart(add_cart_class.java:75)
10-31 12:38:20.484 13886-13886/com.infizoom.infishopping
E/AndroidRuntime: at
android.app.Fragment.performStart(Fragment.java:1724) 10-31
12:38:20.484 13886-13886/com.infizoom.infishopping E/AndroidRuntime:
at
android.app.FragmentManagerImpl.moveToState(FragmentManager.java:918)
10-31 12:38:20.484 13886-13886/com.infizoom.infishopping
E/AndroidRuntime: at
android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
10-31 12:38:20.484 13886-13886/com.infizoom.infishopping
E/AndroidRuntime: at
android.app.BackStackRecord.run(BackStackRecord.java:698) 10-31
12:38:20.484 13886-13886/com.infizoom.infishopping E/AndroidRuntime:
at
android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
10-31 12:38:20.484 13886-13886/com.infizoom.infishopping
E/AndroidRuntime: at
android.app.FragmentManagerImpl$1.run(FragmentManager.java:443) 10-31
12:38:20.484 13886-13886/com.infizoom.infishopping E/AndroidRuntime:
at android.os.Handler.handleCallback(Handler.java:808) 10-31
12:38:20.484 13886-13886/com.infizoom.infishopping E/AndroidRuntime:
at android.os.Handler.dispatchMessage(Handler.java:103) 10-31
12:38:20.484 13886-13886/com.infizoom.infishopping E/AndroidRuntime:
at android.os.Looper.loop(Looper.java:193) 10-31 12:38:20.484
13886-13886/com.infizoom.infishopping E/AndroidRuntime: at
android.app.ActivityThread.main(ActivityThread.java:5341) 10-31
12:38:20.484 13886-13886/com.infizoom.infishopping E/AndroidRuntime:
at java.lang.reflect.Method.invokeNative(Native Method) 10-31
12:38:20.484 13886-13886/com.infizoom.infishopping E/AndroidRuntime:
at java.lang.reflect.Method.invoke(Method.java:515) 10-31 12:38:20.484
13886-13886/com.infizoom.infishopping E/AndroidRuntime: at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
10-31 12:38:20.484 13886-13886/com.infizoom.infishopping
E/AndroidRuntime: at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641) 10-31
12:38:20.484 13886-13886/com.infizoom.infishopping E/AndroidRuntime:
at dalvik.system.NativeStart.main(Native Method)
add_to_cart_display.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_marginTop="#dimen/abc_action_bar_default_height_material"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/recyclerView"
android:layout_width="fill_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
/>
Remove Button inside the CardView
final View view = inflater.inflate(R.layout.add_to_cart_display, container, false);
Button remove=(Button) view.findViewById(R.id.remove_cart_items);
you are looking for a Button with id remove_cart_items inside add_to_cart_display. But in layout may be there is no Button with id remove_cart_items. That`s way you get null
I got an answer. i can access the button inside the cardview by recyclerAdapter onBindViewHolder(). but i dnot know how to call toast in side this function.
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView product_name_at_cart;
public Button remove;
public ViewHolder(View layoutview) {
super(layoutview);
remove =(Button) layoutview.findViewById(R.id.remove_cart_items);
product_name_at_cart=(TextView)layoutview.findViewById(R.id.add_cart_item_name);
}
}
OnBindViewHolder
public void onBindViewHolder(ViewHolder viewholder, int position) {
viewholder.product_name_at_cart.setText(mDataset.get(position).getProduct_name());
viewholder.remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("gopal", "Gopal btn click");
Cursor m=ch.getcurrent_id();
if(m.moveToFirst()){
do{
int id=m.getInt(5);
Toast.makeText(???????, "Gopal id " + id, Toast.LENGTH_SHORT).show();
}while (m.moveToNext());
}
}
});
}
What function will came in the Toast Msg.????
In RecyclerAdapter, I have defined a private Activity context.
Then, you can call the Toast.makeText(context, "your message", ...),

Function in fragment makes emulator crash

Error occurs when I place a function inside onCreateView in menu1_Fragment.java. Sorry in advance as I will be placing my logs in as well so it might make my post a bit big so I will tell you the layout. I am new sorry for the loads of questions.
The code works perfectly if I just don't put the function setClick() inside my fragment. quick note the function basically makes my image in menu1_layout.xml a 3 way button aka start stop reset where when you reset, it pops up a toast of exact time you got
1) menu1_Fragment.java
public class menu1_Fragment extends Fragment {
Chronometer mChronometer;
int loop = 0;
double startTime;
double millis;
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
setClick();
return rootview;
}
Button button;
public void setClick() {
mChronometer = (Chronometer) getActivity().findViewById(R.id.aChronometer);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
}
View.OnClickListener mStartListener = new View.OnClickListener() {
public void onClick(View v) {
if (loop == 0) {
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
startTime = System.currentTimeMillis();
loop++;
} else if (loop == 1) {
mChronometer.stop();
millis = System.currentTimeMillis()-startTime;
loop++;
} else if (loop == 2) {
mChronometer.setBase(SystemClock.elapsedRealtime());
Context context = getActivity().getApplicationContext();
CharSequence text = "Your Time is: " + (millis/1000);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
loop = 0;
}
}
};
}
2) LOGS
10-28 16:52:26.552 2912-2912/app.z0nen.menu D/AndroidRuntime: Shutting down VM
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: FATAL EXCEPTION: main
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Process: app.z0nen.menu, PID: 2912
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{app.z0nen.menu/app.z0nen.slidemenu.MyActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.setClick(menu1_Fragment.java:39)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.onCreateView(menu1_Fragment.java:26)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Fragment.performCreateView(Fragment.java:2220)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.BackStackRecord.run(BackStackRecord.java:793)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentController.execPendingActions(FragmentController.java:325)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Activity.performStart(Activity.java:6252)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
10-28 16:52:28.662 2912-2912/? I/Process: Sending signal. PID: 2912 SIG: 9
3) MyActivity.Java
public class MyActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new menu1_Fragment();
break;
case 1:
objFragment = new menu2_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.my, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
4) Menu1_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<Chronometer
android:id="#+id/aChronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:textColor="#111111"
android:layout_marginTop="27dp"
android:layout_below="#+id/stopWatch"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/stopWatch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/stopwatch2"
android:layout_marginTop="38dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
You can't use getActivity() from onCreateView() as the fragment's activity has not been created yet. You should use not use getActivity() until onActivityCreated() is called, or better yet, use the rootview you inflated to do your findViewByID() calls.
Also, you are initializing your button three times. You should get rid on two of them :)
Change
button = (Button) getActivity().findViewById(R.id.stopWatch);
to this:
button = (Button) findViewById(R.id.stopWatch);
Your button is inside your fragment's layout, not the activity's.
EDIT:
Make your button a member variable, so that you could access it from the onCreateView & setClick methods:
private Button mButton;
And we need to save a reference of your button in the onCreateView method to this: (rootview is your fragment's inflated layout)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
mButton = rootview.findViewById(R.id.stopWatch);
setClick();
return rootview;
}
and in the setClick method put this instead :
mButton.setOnClickListener(mStartListener);

Why DrawerLayout and ActionBar not working on Tablets?

I'm develop some app with sliding menu.
when i try to run this on my galaxy 4s(api 18+ 4.3.3) its work fine!
but when i run this on xperia arc (api 8 ver 2.3.4) the app crash.
i know its dependent on Support library and i use :
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
and i need to use :
import android.support.v7.app.ActionBar;
so i added to my project the support library and connect the support library to him.
but i dont know how to handle the support and what i need to chage on my code:
my java code (v4){
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
public class MainActivity extends Activity implements OnClickListener, OnLongClickListener , OnTouchListener , OnItemClickListener{
/////////////////
ArrayList<ItemInSetting > listSetting = new ArrayList<ItemInSetting>();
CustomAdapterSetting adapterSetting;
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
//////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingItems();
}
public void settingItems(){
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawer = (DrawerLayout) findViewById(R.id.drawer);
toggle = new ActionBarDrawerToggle(this, drawer, R.drawable.ic_drawer, 0, 0){
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("menu");
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
getActionBar().setTitle("app title");
invalidateOptionsMenu();
}
};drawer.setDrawerListener(toggle);
listSetting.add(new ItemInSetting("ist1", R.drawable.calende_bigg));
listSetting.add(new ItemInSetting("ist2", R.drawable.calende_bigg));
listSetting.add(new ItemInSetting("ist3", R.drawable.calende_bigg));
listSetting.add(new ItemInSetting("ist4", R.drawable.calende_bigg));
lvSetting = (ListView) findViewById(R.id.listSetting);
lvSetting.setOnItemClickListener(this);
adapterSetting = new CustomAdapterSetting(listSetting, this);
lvSetting.setAdapter(adapterSetting);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
date = new Date();
switch (position) {
case 0:
Intent intent = new Intent (MainActivity.this,ListOfHours.class);
startActivity(intent);
break;
case 1:
getSetting();
if(sickIsOn){
cancelingFreeday(false);
}else{
addingManualMenu();
}
break;
case 2:
changingSetting(" ");
break;
case 3:
sendContact();
break;
default:
break;
}
drawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (toggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
toggle.onConfigurationChanged(newConfig);
}
my xml:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:background="#drawable/new_back"
android:orientation="vertical"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/FrameLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/listSetting"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:background="#android:color/darker_gray"
android:choiceMode="singleChoice"
android:listSelector="#drawable/list_selector" >
</ListView>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bib.workclock"
android:versionCode="52"
android:versionName="3.0.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/icon_new3"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
<activity
android:name="com.bibas.workclock.MainActivity"
android:label="#string/app_name" android:screenOrientation="portrait" android:windowSoftInputMode="adjustPan"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="ListOfHours" ></activity>
<activity android:name="HelpPage"></activity>
<activity android:name="info" android:screenOrientation="portrait"></activity>
</application>
</manifest>
this the locat error when i try to run on xperia :
05-04 01:59:05.058: E/AndroidRuntime(15484): FATAL EXCEPTION: main
05-04 01:59:05.058: E/AndroidRuntime(15484): java.lang.NoSuchMethodError: com.bba.workclock.MainActivity.getActionBar
05-04 01:59:05.058: E/AndroidRuntime(15484): at com.bba.workclock.MainActivity.settingItems(MainActivity.java:1657)
05-04 01:59:05.058: E/AndroidRuntime(15484): at com.bba.workclock.MainActivity.onCreate(MainActivity.java:124)
05-04 01:59:05.058: E/AndroidRuntime(15484): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-04 01:59:05.058: E/AndroidRuntime(15484): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
05-04 01:59:05.058: E/AndroidRuntime(15484): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
05-04 01:59:05.058: E/AndroidRuntime(15484): at android.app.ActivityThread.access$1500(ActivityThread.java:121)
05-04 01:59:05.058: E/AndroidRuntime(15484): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
05-04 01:59:05.058: E/AndroidRuntime(15484): at android.os.Handler.dispatchMessage(Handler.java:99)
05-04 01:59:05.058: E/AndroidRuntime(15484): at android.os.Looper.loop(Looper.java:130)
05-04 01:59:05.058: E/AndroidRuntime(15484): at android.app.ActivityThread.main(ActivityThread.java:3701)
05-04 01:59:05.058: E/AndroidRuntime(15484): at java.lang.reflect.Method.invokeNative(Native Method)
05-04 01:59:05.058: E/AndroidRuntime(15484): at java.lang.reflect.Method.invoke(Method.java:507)
05-04 01:59:05.058: E/AndroidRuntime(15484): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
05-04 01:59:05.058: E/AndroidRuntime(15484): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
05-04 01:59:05.058: E/AndroidRuntime(15484): at dalvik.system.NativeStart.main(Native Method)
here is project like mine:
http://speedy.sh/UKsrV/SlidingMenu.zip
if any one can fix that code and give it to me back i appreciate alot
How can i fix this?!!
please help me :(((
I FIX THAT PROBLEM BUT KNOW ON MY TABLET IT'S CRASH .
here the locat error:
05-11 23:10:22.127: E/AndroidRuntime(31723): FATAL EXCEPTION: main
05-11 23:10:22.127: E/AndroidRuntime(31723): java.lang.IllegalStateException: Child android.widget.FrameLayout#41f91e40 at index 0 does not have a valid layout_gravity - must be Gravity.LEFT, Gravity.RIGHT or Gravity.NO_GRAVITY
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:721)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.View.measure(View.java:15479)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4826)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.View.measure(View.java:15479)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.View.measure(View.java:15479)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4826)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
05-11 23:10:22.127: E/AndroidRuntime(31723): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2359)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.View.measure(View.java:15479)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1968)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1214)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1387)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4464)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.Choreographer.doFrame(Choreographer.java:525)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.os.Handler.handleCallback(Handler.java:615)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.os.Handler.dispatchMessage(Handler.java:92)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.os.Looper.loop(Looper.java:137)
05-11 23:10:22.127: E/AndroidRuntime(31723): at android.app.ActivityThread.main(ActivityThread.java:4895)
05-11 23:10:22.127: E/AndroidRuntime(31723): at java.lang.reflect.Method.invokeNative(Native Method)
05-11 23:10:22.127: E/AndroidRuntime(31723): at java.lang.reflect.Method.invoke(Method.java:511)
05-11 23:10:22.127: E/AndroidRuntime(31723): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
05-11 23:10:22.127: E/AndroidRuntime(31723): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
05-11 23:10:22.127: E/AndroidRuntime(31723): at dalvik.system.NativeStart.main(Native Method)
ActionBar is available from api level 11. To support below api level 11 you need to use AppCompat from the support library. Reference AppCompat in your android project.
You need to extend ActionBarActivity. Use theme derived from Theme.AppCompat in manifest and use getSupportActionBar().
Complete example #
Navigation Drawer with backword compatibility android
Check Adding libraries with resources
https://developer.android.com/tools/support-library/setup.html
And read
http://developer.android.com/guide/topics/ui/actionbar.html

Android not creating file

I want this fragment to write to a csv file when a button is clicked but I keep getting java.io.IOException: open failed:ENOENT (No such file or directory). Any help would be greatly appreciated.
public class AddFragment extends Fragment {
static EditText spent,saved,coupons;
Button writeExcelButton;
String data;
Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_layout, container, false);
setSpinnerContent(view);
spent = (EditText) view.findViewById(R.id.spent1);
saved = (EditText) view.findViewById(R.id.saved1);
coupons = (EditText) view.findViewById(R.id.coupons1);
writeExcelButton = (Button) view.findViewById(R.id.button_addGroc);
writeExcelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateSheet();
}
});
return view;
}
private void setSpinnerContent (View view) {
spinner = (Spinner) view.findViewById(R.id.groc_store);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.store1, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void updateSheet() {
try {
// This is the string that should be written to file
String mySpin =spinner.getSelectedItem().toString();
data = mySpin + "," + spent.getText().toString() + "," + saved.getText().toString() + "," + coupons.getText().toString() + "/n";
// This is the file that should be written to
String sdCard = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdCard + "/dir");
if (!dir.exists()) {
dir.mkdir();
}
File myFile = new File(dir.getAbsolutePath(), "savings.csv");
// if file doesn't exists, then create it
if (!myFile.exists()) {
myFile.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is what my LogCat looks like
11-14 13:29:23.681: W/System.err(14386): java.io.IOException: open failed: ENOENT (No such file or directory)
11-14 13:29:23.681: W/System.err(14386): at java.io.File.createNewFile(File.java:948)
11-14 13:29:23.691: W/System.err(14386): at com.example.myfirstapp.AddFragment.updateSheet(AddFragment.java:101)
11-14 13:29:23.691: W/System.err(14386): at com.example.myfirstapp.AddFragment$1.onClick(AddFragment.java:59)
11-14 13:29:23.691: W/System.err(14386): at android.view.View.performClick(View.java:4240)
11-14 13:29:23.691: W/System.err(14386): at android.view.View$PerformClick.run(View.java:17721)
11-14 13:29:23.691: W/System.err(14386): at android.os.Handler.handleCallback(Handler.java:730)
11-14 13:29:23.691: W/System.err(14386): at android.os.Handler.dispatchMessage(Handler.java:92)
11-14 13:29:23.691: W/System.err(14386): at android.os.Looper.loop(Looper.java:137)
11-14 13:29:23.691: W/System.err(14386): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-14 13:29:23.691: W/System.err(14386): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 13:29:23.691: W/System.err(14386): at java.lang.reflect.Method.invoke(Method.java:525)
11-14 13:29:23.701: W/System.err(14386): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-14 13:29:23.711: W/System.err(14386): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 13:29:23.711: W/System.err(14386): at dalvik.system.NativeStart.main(Native Method)
11-14 13:29:23.711: W/System.err(14386): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
11-14 13:29:23.711: W/System.err(14386): at libcore.io.Posix.open(Native Method)
11-14 13:29:23.711: W/System.err(14386): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
11-14 13:29:23.711: W/System.err(14386): at java.io.File.createNewFile(File.java:941)
Try changing
dir.mkdir();
to
dir.mkdirs();
Also try just passing dir instead of dir.getAbsolutePath()
Edit
Also you don't want to concatanate file paths like that. Try:
File myFile = new File(Environment.getExternalStorageDirectory(), "dir/savings.csv");
if (!myFile.exists()) {
myFile.mkdirs();
myFile.createNewFile();
}
Add this permissions in manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

AsyncTask #1 :An error occured while executing doInBackground()

I am developing app with Jsoup. The problem is it is not working when I am calling it from other class with the help of Getters. But it is running when I call it within Single Activity. I am not able to find why exactly it is not working, as it should.
Here are the logCat files with all the activities.
LogCat
11-14 20:16:52.063: E/AndroidRuntime(1871): FATAL EXCEPTION: AsyncTask #1
11-14 20:16:52.063: E/AndroidRuntime(1871): java.lang.RuntimeException: An error occured while executing doInBackground()
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.lang.Thread.run(Thread.java:856)
11-14 20:16:52.063: E/AndroidRuntime(1871): Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.Jsoup.connect(Jsoup.java:73)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-14 20:16:52.063: E/AndroidRuntime(1871): ... 4 more
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(getApplicationContext(), LineGraph.class);
startActivity(i);
}
}
LineGraph
public class LineGraph extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
jsoupAct mJsoupAct = new jsoupAct();
String parseStrings;
parseStrings = mJsoupAct.getOutput();
Log.d("xstring", parseStrings + "");
}
}
jsoupAct
public class jsoupAct extends Activity {
String output = "00";
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
url = "www.google.com";
}
public void mExecute() {
new Parsee().execute();
}
public class Parsee extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(url).get();
String body = doc.body().text();
output = body.toString();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(output);
}
}
public String getOutput() {
mExecute();
return output;
}
public void setOutput(String output) {
this.output = output;
}
}
You are specifying the URL in a string local to the jsoupAct activity. The string will be null if you try to access from other Activities. To solve it move the string inside the AsyncTask class and it will work
Or add empty constructor to the jsonAct activity and assign the value of url in it. onCreate() is called only when to start an activity using the startActivity()
You have already answered your own question:
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more

Categories