I'm writing an app that show accelerometer readings, I was able yesterday to write all the accelerometer code in the main activity and it works fine on emulator and my device.
But today I was trying to make a function that contains all the accelerometer code and return the three integers X,Y,Z in integer array, so I make a code that I think it`s right but every time I run the project the emulator gives an error "Unfortunately app-name has stopped" .
So I wish any help , please .
LogCat:
04-27 20:39:27.098: W/dalvikvm(812): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
04-27 20:39:27.118: E/AndroidRuntime(812): FATAL EXCEPTION: main
04-27 20:39:27.118: E/AndroidRuntime(812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.accelerometer_sensor/com.example.accelerometer_sensor.MainActivity}: java.lang.NullPointerException
04-27 20:39:27.118: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-27 20:39:27.118: E/AndroidRuntime(812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-27 20:39:27.118: E/AndroidRuntime(812): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-27 20:39:27.118: E/AndroidRuntime(812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-27 20:39:27.118: E/AndroidRuntime(812): at android.os.Handler.dispatchMessage(Handler.java:99)
04-27 20:39:27.118: E/AndroidRuntime(812): at android.os.Looper.loop(Looper.java:137)
04-27 20:39:27.118: E/AndroidRuntime(812): at android.app.ActivityThread.main(ActivityThread.java:5039)
04-27 20:39:27.118: E/AndroidRuntime(812): at java.lang.reflect.Method.invokeNative(Native Method)
04-27 20:39:27.118: E/AndroidRuntime(812): at java.lang.reflect.Method.invoke(Method.java:511)
04-27 20:39:27.118: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-27 20:39:27.118: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-27 20:39:27.118: E/AndroidRuntime(812): at dalvik.system.NativeStart.main(Native Method)
04-27 20:39:27.118: E/AndroidRuntime(812): Caused by: java.lang.NullPointerException
04-27 20:39:27.118: E/AndroidRuntime(812): at com.example.accelerometer_sensor.AccelerometerClass.AccelerometerInit(AccelerometerClass.java:20)
04-27 20:39:27.118: E/AndroidRuntime(812): at com.example.accelerometer_sensor.MainActivity.onCreate(MainActivity.java:19)
04-27 20:39:27.118: E/AndroidRuntime(812): at android.app.Activity.performCreate(Activity.java:5104)
04-27 20:39:27.118: E/AndroidRuntime(812): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-27 20:39:27.118: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-27 20:39:27.118: E/AndroidRuntime(812): ... 11 more
04-27 20:39:30.119: I/Process(812): Sending signal. PID: 812 SIG: 9
here`s my main activity code:
package com.example.accelerometer_sensor;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
int [] AccVal = new int[3];
AccelerometerClass acc = new AccelerometerClass();
TextView acceleration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acc = new AccelerometerClass();
AccVal = acc.AccelerometerInit();
acceleration = (TextView)findViewById(R.id.acceleration);
acceleration.setText("X: "+AccVal[0]+
"Y: "+AccVal[1]+
"Z: "+AccVal[2]);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and this is my AccelerometerClass Code ::
package com.example.accelerometer_sensor;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class AccelerometerClass implements SensorEventListener
{
private static Context context;
int [] Vals = new int[3];
public int [] AccelerometerInit()
{
Sensor accelerometer;
SensorManager sm;
sm = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
return Vals;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
Vals[0]=(int)event.values[0];
Vals[1]=(int)event.values[1];
Vals[2]=(int)event.values[2];
}
}
Thanks .
Your context in AccelerometerClass is never set!
Possible solution:
public class AccelerometerClass implements SensorEventListener {
int[] Vals = new int[3];
public int[] AccelerometerInit(Context context) {
SensorManager sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
return Vals;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
Vals[0] = (int) event.values[0];
Vals[1] = (int) event.values[1];
Vals[2] = (int) event.values[2];
}
}
in your Activity use
AccelerometerClass ac = new AccelerometerClass();
ac.AccelerometerInit(this);
Related
I have popupMenu and CheckBox. I need make write status CheckBox to boolean.
This code not working:
MenuItem fast_result;
boolean fast=false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.FastResult:
fast_result = item.getSubMenu().getItem(R.id.FastResult);//This is 182 line
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
}
}
It is errors:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.alexvsalex.HelpforMath.RootsActivity.onOptionsItemSelected(RootsActivity.java:182)
at android.app.Activity.onMenuItemSelected(Activity.java:2502)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:950)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:163)
at android.widget.AdapterView.performItemClick(AdapterView.java:292)
at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
at android.widget.AbsListView$1.run(AbsListView.java:3168)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
What to do?
The problem is solved:
case R.id.FastResult:
fast_result = item; //There was an error
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
I am learning android programming and created a basic project using android studio.
My application crashes when I click on the getdata button.
The MainActivity.java:
package com.cs_infotech.newpathshala;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity
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_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().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) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ExampleFragment();
break;
case 1:
fragment = new Example1Fragment();
break;
case 2:
fragment = new Example2Fragment();
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
} }
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = "ePathshala";
break;
case 2:
mTitle = "Daily Collection";
break;
case 3:
mTitle = "New Enrolled";
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
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.main, 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_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
test1.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"
android:orientation="vertical" >
<Button
android:id="#+id/getdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:text="Get Data" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/getdata" />
<TextView
android:id="#+id/vers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/api"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Example1Fragment.java:
package com.cs_infotech.newpathshala;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.cs_infotech.newpathshala.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Example1Fragment extends Fragment {
ListView list;
TextView ver;
TextView name;
TextView api;
Button btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://api.learn2crack.com/android/jsonos/";
//JSON Node Names
private static final String TAG_OS = "android";
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
JSONArray android = null;
private View v;
public Example1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.test1, container, false);
oslist = new ArrayList<HashMap<String, String>>();
btngetdata = (Button) rootView.findViewById(R.id.getdata);
v=rootView;
btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
//Toast.makeText(getActivity(), "You Clicked at " , Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name = (TextView) v.findViewById(R.id.name);
ver = (TextView) v.findViewById(R.id.vers);
api = (TextView) v.findViewById(R.id.api);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl("http://api.learn2crack.com/android/jsonos/");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView) v.findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(), "You Clicked at " + oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Logcat:
04-10 10:12:52.253 30126-30126/com.cs_infotech.newpathshala D/ActivityThread﹕ handleBindApplication:com.cs_infotech.newpathshala
04-10 10:12:52.343 30126-30126/com.cs_infotech.newpathshala W/ApplicationPackageManager﹕ getCSCPackageItemText()
04-10 10:12:52.343 30126-30126/com.cs_infotech.newpathshala D/DisplayManager﹕ DisplayManager()
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 11359: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 11365: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
04-10 10:12:52.433 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
04-10 10:12:52.433 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 9053: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
04-10 10:12:52.433 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 374: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 396: Landroid/content/res/TypedArray;.getType (I)I
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
04-10 10:12:52.834 30126-30126/com.cs_infotech.newpathshala D/OpenGLRenderer﹕ Enabling debug mode 0
04-10 10:12:52.934 30126-30126/com.cs_infotech.newpathshala I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#41e049e0 time:9101016
04-10 10:15:04.772 30126-30126/com.cs_infotech.newpathshala I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#41e049e0 time:9232856
04-10 10:15:11.359 30126-30656/com.cs_infotech.newpathshala W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x416c8bc0)
04-10 10:15:11.379 30126-30656/com.cs_infotech.newpathshala E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.cs_infotech.newpathshala, PID: 30126
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.cs_infotech.newpathshala.JSONParser.getJSONFromUrl(JSONParser.java:44)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:80)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:62)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.cs_infotech.newpathshala.JSONParser.getJSONFromUrl(JSONParser.java:44)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:80)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:62)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.cs_infotech.newpathshala.JSONParser.getJSONFromUrl(JSONParser.java:44)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:80)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:62)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
04-10 10:15:12.330 30126-30126/com.cs_infotech.newpathshala E/OpenGLRenderer﹕ SFEffectCache:clear(), mSize = 0
04-10 10:15:12.360 30126-30126/com.cs_infotech.newpathshala E/WindowManager﹕ android.view.WindowLeaked: Activity com.cs_infotech.newpathshala.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e91890 V.E..... R......D 0,0-471,144} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.onPreExecute(Example1Fragment.java:74)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.cs_infotech.newpathshala.Example1Fragment$1.onClick(Example1Fragment.java:56)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
04-10 10:15:14.992 30126-30656/com.cs_infotech.newpathshala I/Process﹕ Sending signal. PID: 30126 SIG: 9
How can I resolve this?
I follow this example about adding DatePicker to my app when using Android Studio.
import android.support.v4.app.DialogFragment;
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
The problem is that I can not even compile the project. Here is the error:
Error:(6, 42) java: cannot find symbol
symbol: class DialogFragment
Error:(7, 36) java: package DatePickerDialog does not exist
I tried import android.support.v4.app.DialogFragment;, but it does not exist. Also I set my project to API 11 as that is minimum api level for this control. Any ideas?
I got datePicker somehow working but now I have error when opening activity that contains datepicker:
07-16 18:17:36.274 1822-1822/mycalories.com.jalle.mycalories D/AndroidRuntime﹕ Shutting down VM
07-16 18:17:36.274 1822-1822/mycalories.com.jalle.mycalories W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4db2b20)
07-16 18:17:36.274 1822-1822/mycalories.com.jalle.mycalories E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: mycalories.com.jalle.mycalories, PID: 1822
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{mycalories.com.jalle.mycalories/mycalories.com.jalle.mycalories.MealsEditActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at mycalories.com.jalle.mycalories.MealsEditActivity.<init>(MealsEditActivity.java:23)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
and here is the activity
package mycalories.com.jalle.mycalories;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.parse.Parse;
import com.parse.ParseUser;
//import android.app.DialogFragment;
public class MealsEditActivity extends FragmentActivity implements mycalories.com.jalle.mycalories.DatePickerFragment.TheListener{
public final EditText txtDate=(EditText) findViewById(R.id.txtDate);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.meals_edit);
Button btnDate = (Button) findViewById(R.id.btnDate);
btnDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Utils.MyToast("btnDate", getApplicationContext());
DialogFragment newFragment = new com.jalle.mycalories.DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
);
}
public void returnDate(String date) {
// TODO Auto-generated method stub
txtDate.setText(date);
}
}
}
What is wrong with this activity ?
have you add android support library to build.gradle of your application ?
for example :
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:+'
}
then try to rebuild it.
For exception :
put
public final EditText txtDate=(EditText) findViewById(R.id.txtDate);
this line below
setContentView(R.layout.meals_edit);
List View doesn't work in Fragment.
Fragment.java
public class Fragment_Main extends Fragment{
ArrayAdapter<String> categoryAdapter;
ArrayList<String> categoryList = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View View = inflater.inflate(R.layout.fragment_main, container, false);
ListView list = (ListView) getView().findViewById(R.id.listView1);
categoryAdapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, categoryList);
list.setAdapter(categoryAdapter);
showCategoryTask task=new showCategoryTask();
task.execute();
return View;
}
class showCategoryTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://garyhui86.er-webs.com/index.xml");
HttpURLConnection urlConn =
(HttpURLConnection)url.openConnection();
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
DocumentBuilder builder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
Document document = builder.parse(urlConn.getInputStream());
NodeList nodeList = document.getElementsByTagName("Info");
for (int i = 0; i < nodeList.getLength(); i++) {
NamedNodeMap attributes=nodeList.item(i).getAttributes();
String category=attributes.getNamedItem("categoryName").getNodeValue();
Log.i("ttt", category);
categoryList.add(category);
}
}
urlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
categoryAdapter.notifyDataSetChanged();
}
}
}
Error Log:
04-27 15:39:02.568: E/AndroidRuntime(7826): FATAL EXCEPTION: main
04-27 15:39:02.568: E/AndroidRuntime(7826): java.lang.RuntimeException: Unable to start activity ComponentInfo{hkpro.shopdada.com.summonboardinfo/hkpro.shopdada.com.summonboardinfo.MainActivity}: java.lang.NullPointerException
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.os.Handler.dispatchMessage(Handler.java:99)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.os.Looper.loop(Looper.java:137)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-27 15:39:02.568: E/AndroidRuntime(7826): at java.lang.reflect.Method.invokeNative(Native Method)
04-27 15:39:02.568: E/AndroidRuntime(7826): at java.lang.reflect.Method.invoke(Method.java:511)
04-27 15:39:02.568: E/AndroidRuntime(7826): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-27 15:39:02.568: E/AndroidRuntime(7826): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-27 15:39:02.568: E/AndroidRuntime(7826): at dalvik.system.NativeStart.main(Native Method)
04-27 15:39:02.568: E/AndroidRuntime(7826): Caused by: java.lang.NullPointerException
04-27 15:39:02.568: E/AndroidRuntime(7826): at hkpro.shopdada.com.summonboardinfo.Fragment_Main.onCreateView(Fragment_Main.java:39)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1164)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.app.Activity.performStart(Activity.java:5114)
04-27 15:39:02.568: E/AndroidRuntime(7826): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
04-27 15:39:02.568: E/AndroidRuntime(7826): ... 11 more
Use the inflated object to find the 'ListView'.
Do it like this:
'ListView list = (ListView) inflated_layout_object.findViewById(R.id.listView1);'
Here for you inflated_layout_object is View (which you have created).
This lines causes trouble I guess:
View View = inflater.inflate(R.layout.fragment_main, container, false);
ListView list = (ListView) getView().findViewById(R.id.listView1);
Don't use the getView() method to find Views by Id. Use the inflated layout instead:
View root = inflater.inflate(R.layout.fragment_main, container, false);
ListView list = (ListView) root.findViewById(R.id.listView1);
The reason for this is getView() only returns the Fragments View if onCreateView has returned.
I have an app that's supposed to get some string from a server depending on the webpage, and it crashes every time I run it. I don't understand how to even debug it, and I've tried numerous changes. It started crashing ever since I messed with the GUI, and added the ability to switch views if that provides any sort of help.
Here is the code:
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnClickListener{
private WebView mWebview;
EditText addressBar;
String currentWebpage = "http://www.aljazeera.com/news/americas/2013/07/20137113200544375.html";
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
View main = (View) findViewById(R.layout.activity_main);
View readOut = (View) findViewById(R.layout.read_out);
#Override
public void onCreate(Bundle savedInstanceState) {
System.out.println("Showing Activity_Main...");
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
super.onCreate(savedInstanceState);
//setContentView(R.menu.main);
addressBar = (EditText)findViewById(R.id.addressBar);
addressBar.setText(currentWebpage);
mWebview = (WebView)findViewById(R.id.webview);
mWebview.getSettings().setJavaScriptEnabled(true); // enables javascript
mWebview.setWebViewClient(new WebViewClient());
System.out.println("Loading Webpage...");
mWebview.loadUrl(currentWebpage);
}
public void speakOut(String text) {
TextToSpeech tts = new TextToSpeech(this, this);
System.out.println("Speaking");
if(tts.isLanguageAvailable(Locale.ENGLISH) != -1){
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
public int speakFull(String text){
switchToRead();
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
speakOut(sentences[i]);
if(i == sentences.length - 1){
return 1;
}
}
return 0;
}
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://someserver.net:8080/" + webPage));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
private class tts extends AsyncTask<String, Void, String>{//Async http request to get text
#Override
protected String doInBackground(String... arg0) {
try {
System.out.println("Running seperate thread for TTS.");
int complete = 0;
while(complete == 0){
System.out.println("Speaking full..");
complete = speakFull(getText(mWebview.getUrl()));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
}
}
public void clickPlay(View v){
new tts().execute("");
}
public void clickGo(View v){
if(addressBar.getText() != null){
currentWebpage = addressBar.getText().toString();
System.out.println("Current webpage changed to: " + currentWebpage);
mWebview.loadUrl(currentWebpage);
}
}
public void clickPause(View v){
System.out.println("Clicked pause.");
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
System.out.println("Swtiching view to Read.");
viewGroup.removeView(main);
viewGroup.addView(View.inflate(this, R.layout.read_out, null));
}
public void switchToMain(){
System.out.println("Switching view to Main.");
viewGroup.removeView(readOut);
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
}
}
Also here are the numerous errors I encounter when launching my app:
08-01 14:53:10.210: E/Trace(812): error opening trace file: No such file or directory (2)
08-01 14:53:10.600: D/AndroidRuntime(812): Shutting down VM
08-01 14:53:10.631: W/dalvikvm(812): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:10.660: E/AndroidRuntime(812): FATAL EXCEPTION: main
08-01 14:53:10.660: E/AndroidRuntime(812): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:10.660: E/AndroidRuntime(812): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): Caused by: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:10.660: E/AndroidRuntime(812): ... 11 more
08-01 14:53:27.439: D/AndroidRuntime(860): Shutting down VM
08-01 14:53:27.439: W/dalvikvm(860): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:27.449: E/AndroidRuntime(860): FATAL EXCEPTION: main
08-01 14:53:27.449: E/AndroidRuntime(860): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:27.449: E/AndroidRuntime(860): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): Caused by: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:27.449: E/AndroidRuntime(860): ... 11 more
Move your view initialization inside onCreate after setContentView
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
...// rest of the code