This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I have a problem.
I want to know where did the android.os.NetworkOnMainThreadException and
java.lang.reflect.InvocationTargetException Exception come from !
Please, I'm new to Android and I need your help guys!
My LogCat:
12-19 13:00:27.049: E/AndroidRuntime(1170): FATAL EXCEPTION: main
12-19 13:00:27.049: E/AndroidRuntime(1170): java.lang.IllegalStateException: Could not execute method of the activity
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3633)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View.performClick(View.java:4240)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$PerformClick.run(View.java:17721)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.handleCallback(Handler.java:730)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Looper.loop(Looper.java:137)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-19 13:00:27.049: E/AndroidRuntime(1170): at dalvik.system.NativeStart.main(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: java.lang.reflect.InvocationTargetException
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3628)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 11 more
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: android.os.NetworkOnMainThreadException
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connect(IoBridge.java:112)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.Socket.connect(Socket.java:842)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.ensem.sehaty.MainActivity.recupererListMed(MainActivity.java:58)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 14 more
12-19 13:05:27.366: I/Process(1170): Sending signal. PID: 1170 SIG: 9
MainActivity.java
public class MainActivity extends Activity {
Button btnRecupListMed = null;
ListView listeMed = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRecupListMed = (Button) findViewById(R.id.btnListMed);
listeMed = (ListView) findViewById(R.id.listMed);
}
public void recupererListMed(View v){
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(sb.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<TextView
android:text="#string/lbl_sehaty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/btnListMed"
android:text="#string/lbl_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="recupererListMed"
/>
<ListView
android:id="#+id/listMed"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginTop="60dp">
</ListView>
And my Manifest contains the following permission
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Thanks.
This error comes when you try to make a server call on UI thread.
You should create an AsyncTask and put your server call in it.
And on click of button call execute on the object of asynctask.
Ex:
public class ServiceTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
return sb;
}
#Override
protected void onPostExecute(String result) {
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(result.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
}
And inside your onClick event:
public void recupererListMed(View v){
new ServiceTask().execute();
}
This will execute doInBackground method on a different thread and once result is fetched onPostExecute is called on UI thread.
Related
I had this Networkonmainthread exception in my activity. I searched for a solution for the problem. While I was searching, I found that I should use AsyncTask. After I tried AsyncTask, I am still facing the same problem.
This is my register activity:
private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
if (params.length != 3)
return null;
JSONObject json = userFunction.registerUser(params[0], params[1], params[2]);
return json;
}
protected void onPostExecute(JSONObject json) {
// check for login response
try {
if (json != null && json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
UserFunctions userFunction = new UserFunctions();
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
new MyAsyncTask().execute(name, email, password);
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
This is my logcat:
09-26 00:56:23.865: D/AndroidRuntime(791): Shutting down VM
09-26 00:56:23.875: W/dalvikvm(791): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-26 00:56:23.925: E/AndroidRuntime(791): FATAL EXCEPTION: main
09-26 00:56:23.925: E/AndroidRuntime(791): android.os.NetworkOnMainThreadException
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
09-26 00:56:23.925: E/AndroidRuntime(791): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
09-26 00:56:23.925: E/AndroidRuntime(791): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-26 00:56:23.925: E/AndroidRuntime(791): at libcore.io.IoBridge.connect(IoBridge.java:112)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.net.Socket.connect(Socket.java:842)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-26 00:56:23.925: E/AndroidRuntime(791): at library.JSONParser.getJSONFromUrl(JSONParser.java:45)
09-26 00:56:23.925: E/AndroidRuntime(791): at library.UserFunctions.registerUser(UserFunctions.java:62)
09-26 00:56:23.925: E/AndroidRuntime(791): at com.example.bustracker.RegisterActivity$1.onClick(RegisterActivity.java:105)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.view.View.performClick(View.java:4084)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.view.View$PerformClick.run(View.java:16966)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.Handler.handleCallback(Handler.java:615)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.Handler.dispatchMessage(Handler.java:92)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.Looper.loop(Looper.java:137)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.app.ActivityThread.main(ActivityThread.java:4745)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.lang.reflect.Method.invokeNative(Native Method)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.lang.reflect.Method.invoke(Method.java:511)
09-26 00:56:23.925: E/AndroidRuntime(791): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-26 00:56:23.925: E/AndroidRuntime(791): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-26 00:56:23.925: E/AndroidRuntime(791): at dalvik.system.NativeStart.main(Native Method)
09-26 00:56:24.215: W/System.err(791): org.apache.http.conn.HttpHostConnectException: Connection to http:// refused
09-26 00:56:24.436: W/System.err(791): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
09-26 00:56:24.546: W/System.err(791): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-26 00:56:24.786: W/System.err(791): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-26 00:56:24.967: W/System.err(791): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-26 00:56:24.995: W/System.err(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-26 00:56:25.017: W/System.err(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-26 00:56:25.017: W/System.err(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-26 00:56:25.165: W/System.err(791): at library.JSONParser.getJSONFromUrl(JSONParser.java:45)
09-26 00:56:25.235: W/System.err(791): at library.UserFunctions.registerUser(UserFunctions.java:62)
09-26 00:56:25.264: W/System.err(791): at com.example.bustracker.RegisterActivity$MyAsyncTask.doInBackground(RegisterActivity.java:43)
09-26 00:56:25.265: W/System.err(791): at com.example.bustracker.RegisterActivity$MyAsyncTask.doInBackground(RegisterActivity.java:1)
09-26 00:56:25.285: W/System.err(791): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-26 00:56:25.305: W/System.err(791): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-26 00:56:25.535: W/System.err(791): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-26 00:56:25.535: W/System.err(791): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-26 00:56:25.675: W/System.err(791): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-26 00:56:25.956: W/System.err(791): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-26 00:56:26.115: W/System.err(791): at java.lang.Thread.run(Thread.java:856)
09-26 00:56:26.147: W/System.err(791): Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 8888): connect failed: ECONNREFUSED (Connection refused)
09-26 00:56:26.226: W/System.err(791): at libcore.io.IoBridge.connect(IoBridge.java:114)
09-26 00:56:26.226: W/System.err(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-26 00:56:26.236: W/System.err(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-26 00:56:26.236: W/System.err(791): at java.net.Socket.connect(Socket.java:842)
09-26 00:56:26.246: W/System.err(791): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-26 00:56:26.255: W/System.err(791): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-26 00:56:26.255: W/System.err(791): ... 17 more
09-26 00:56:26.266: W/System.err(791): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
09-26 00:56:26.276: W/System.err(791): at libcore.io.Posix.connect(Native Method)
09-26 00:56:26.286: W/System.err(791): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
09-26 00:56:26.286: W/System.err(791): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-26 00:56:26.286: W/System.err(791): at libcore.io.IoBridge.connect(IoBridge.java:112)
09-26 00:56:26.296: W/System.err(791): ... 22 more
09-26 00:56:26.296: E/Buffer Error(791): Error converting result java.lang.NullPointerException
09-26 00:56:26.305: E/JSON Parser(791): Error parsing data org.json.JSONException: End of input at character 0 of
09-26 00:56:27.146: I/Process(791): Sending signal. PID: 791 SIG: 9
What am I doing wrong?
The stacktrace says you're calling a network operation in getJSONFromUrl() and calling that on the UI thread in registerUser(). The code here looks to be the culprit:
new MyAsyncTask().execute(name, email, password);
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
You're first invoking the registerUser() in a background asynctask (good!) and then only a couple of lines later doing the same again on the main thread (bad!). Remove the latter.
I bet userFunction.logoutUser(getApplicationContext()); issues network request to logout user thus error caused by accessing network on main thread (onPostResult runs on ui thread, in contrary to doInBackground)
According to the code in your post, you're still calling userFunction.registerUser directly from inside of the onClickListener handler - right after calling MyAsyncTask.execute. It's that registerUser call that the logcat output is complaining about, not the one in the AsyncTask. Did you mean to delete the duplicate call from the onClickListener handler after you moved that logic to the AsyncTask?
I am trying to retrieve data by clicking on a button in my activity. I have declared an onclick in activity_second.Here is my code.I am getting am IllegalstateException: method cannot be executed in activity.what is wrong with my code.Why the logcat is showing InvocationTargetException.what exactly this error is and why NullPointerException is there??
public class SecondActivity extends Activity {
private EditText loadinfo;
private Button butn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
loadinfo = (EditText)findViewById(R.id.editText1);
butn1 = (Button)findViewById(R.id.button1);
}
public void apurv1(View view){
File folder = getCacheDir();
File myfile = new File(folder, "mydata1.txt");
String data = readdata(myfile);
if(data!=null){
loadinfo.setText(data);
}
else {
loadinfo.setText("no entry was done");
}
}
private String readdata(File myfile){
FileInputStream fis= null;
try {
fis = new FileInputStream(myfile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int read = -1;
StringBuffer stringbuffer = new StringBuffer();
try {
while((read = fis.read())!=-1){
stringbuffer.append((char)read);
}
return stringbuffer.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (fis!=null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
StackTrace is
04-26 00:59:00.545: E/AndroidRuntime(2023): FATAL EXCEPTION: main
04-26 00:59:00.545: E/AndroidRuntime(2023): java.lang.IllegalStateException: Could not execute method of the activity
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.view.View$1.onClick(View.java:3633)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.view.View.performClick(View.java:4240)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.view.View$PerformClick.run(View.java:17721)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.os.Handler.handleCallback(Handler.java:730)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.os.Handler.dispatchMessage(Handler.java:92)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.os.Looper.loop(Looper.java:137)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-26 00:59:00.545: E/AndroidRuntime(2023): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 00:59:00.545: E/AndroidRuntime(2023): at java.lang.reflect.Method.invoke(Method.java:525)
04-26 00:59:00.545: E/AndroidRuntime(2023): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-26 00:59:00.545: E/AndroidRuntime(2023): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-26 00:59:00.545: E/AndroidRuntime(2023): at dalvik.system.NativeStart.main(Native Method)
04-26 00:59:00.545: E/AndroidRuntime(2023): Caused by: java.lang.reflect.InvocationTargetException
04-26 00:59:00.545: E/AndroidRuntime(2023): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 00:59:00.545: E/AndroidRuntime(2023): at java.lang.reflect.Method.invoke(Method.java:525)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.view.View$1.onClick(View.java:3628)
04-26 00:59:00.545: E/AndroidRuntime(2023): ... 11 more
04-26 00:59:00.545: E/AndroidRuntime(2023): Caused by: java.lang.NullPointerException
04-26 00:59:00.545: E/AndroidRuntime(2023): at com.example.storageexternal.SecondActivity.readdata(SecondActivity.java:62)
04-26 00:59:00.545: E/AndroidRuntime(2023): at com.example.storageexternal.SecondActivity.apurv1(SecondActivity.java:36)
04-26 00:59:00.545: E/AndroidRuntime(2023): ... 14 more
Assuming activity_second is your xml file and you have an attribute android:onClick="readdate" for your button, your readdate method should return void and have an argument of View, such as
public void readdate (View v) {
//add code
}
or via an OnClickListener
Check this post for more details How exactly does the android:onClick XML attribute differ from setOnClickListener?
this is the code...plz let me know where did i go wrong.. also i am setting an adapter to the listview which is conatined in the View v1 inflated...this is all done in the extension response of a smartfox server...and then the following process on UI Thread..
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
alert();
}
});
public void alert(){
AlertDialog.Builder ab=new AlertDialog.Builder(RegActivity.this);
LayoutInflater linf=(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View v1=linf.inflate(R.layout.proj_list, null);
ab.setView(v1);
ab.setTitle("Select a group");
ListView lvprojlist=(ListView) findViewById(R.id.projdisplaylist);
adplist=new ArrayAdapter<String>(RegActivity.this, R.layout.list_item, R.id.rowtext, projlist);
lvprojlist.setAdapter(adplist);
ab.setCancelable(false).setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
ab.create();
ab.show();
}
this is my logcat output..
12-19 17:14:33.869: W/dalvikvm(699): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-19 17:14:33.889: E/AndroidRuntime(699): FATAL EXCEPTION: main
12-19 17:14:33.889: E/AndroidRuntime(699): java.lang.NullPointerException
12-19 17:14:33.889: E/AndroidRuntime(699): at com.registersfsmodule.RegActivity.alert(RegActivity.java:392)
12-19 17:14:33.889: E/AndroidRuntime(699): at com.registersfsmodule.RegActivity$3$2.run(RegActivity.java:178)
12-19 17:14:33.889: E/AndroidRuntime(699): at android.os.Handler.handleCallback(Handler.java:587)
12-19 17:14:33.889: E/AndroidRuntime(699): at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 17:14:33.889: E/AndroidRuntime(699): at android.os.Looper.loop(Looper.java:130)
12-19 17:14:33.889: E/AndroidRuntime(699): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-19 17:14:33.889: E/AndroidRuntime(699): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 17:14:33.889: E/AndroidRuntime(699): at java.lang.reflect.Method.invoke(Method.java:507)
12-19 17:14:33.889: E/AndroidRuntime(699): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-19 17:14:33.889: E/AndroidRuntime(699): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-19 17:14:33.889: E/AndroidRuntime(699): at dalvik.system.NativeStart.main(Native Method)
You have to first change this in reverse order.
ab.setTitle("Select a group");
ListView lvprojlist=(ListView) v1.findViewById(R.id.projdisplaylist);
ab.setView(v1);
You have to set view after find id of your ListView.
Also don't make adplist variable globally. Make it static.
ArrayAdapter<String >adplist=new ArrayAdapter<String>(RegActivity.this, R.layout.list_item, R.id.rowtext, projlist);
I'm trying to save a webpage to my external storage with the following method:
public void saveWebPage(String url, String fileName){
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
String resString = sb.toString();
is.close();
File file = new File(Environment.getExternalStorageDirectory().toString() + "/Android/data/com.whizzapps.stpsurniki/" + fileName + ".html");
file.createNewFile();
FileOutputStream f1 = new FileOutputStream(file, false);
PrintStream p = new PrintStream(f1);
p.print(resString);
p.close();
f1.close();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I call the method, the app crashes and this is the logcat:
09-09 17:26:22.304: E/AndroidRuntime(14507): FATAL EXCEPTION: main
09-09 17:26:22.304: E/AndroidRuntime(14507): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.whizzapps.stpsurniki/com.whizzapps.stpsurniki.Scheudele}: android.os.NetworkOnMainThreadException
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.os.Handler.dispatchMessage(Handler.java:99)
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.os.Looper.loop(Looper.java:137)
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.app.ActivityThread.main(ActivityThread.java:5103)
09-09 17:26:22.304: E/AndroidRuntime(14507): at java.lang.reflect.Method.invokeNative(Native Method)
09-09 17:26:22.304: E/AndroidRuntime(14507): at java.lang.reflect.Method.invoke(Method.java:525)
09-09 17:26:22.304: E/AndroidRuntime(14507): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-09 17:26:22.304: E/AndroidRuntime(14507): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-09 17:26:22.304: E/AndroidRuntime(14507): at dalvik.system.NativeStart.main(Native Method)
09-09 17:26:22.304: E/AndroidRuntime(14507): Caused by: android.os.NetworkOnMainThreadException
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
09-09 17:26:22.304: E/AndroidRuntime(14507): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
09-09 17:26:22.304: E/AndroidRuntime(14507): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-09 17:26:22.304: E/AndroidRuntime(14507): at java.net.InetAddress.getAllByName(InetAddress.java:214)
09-09 17:26:22.304: E/AndroidRuntime(14507): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-09 17:26:22.304: E/AndroidRuntime(14507): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-09 17:26:22.304: E/AndroidRuntime(14507): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-09 17:26:22.304: E/AndroidRuntime(14507): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-09 17:26:22.304: E/AndroidRuntime(14507): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-09 17:26:22.304: E/AndroidRuntime(14507): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-09 17:26:22.304: E/AndroidRuntime(14507): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-09 17:26:22.304: E/AndroidRuntime(14507): at com.whizzapps.stpsurniki.Scheudele.saveWebPage(Scheudele.java:135)
09-09 17:26:22.304: E/AndroidRuntime(14507): at com.whizzapps.stpsurniki.Scheudele.getWebView(Scheudele.java:66)
09-09 17:26:22.304: E/AndroidRuntime(14507): at com.whizzapps.stpsurniki.Scheudele.onCreate(Scheudele.java:50)
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.app.Activity.performCreate(Activity.java:5133)
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-09 17:26:22.304: E/AndroidRuntime(14507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
09-09 17:26:22.304: E/AndroidRuntime(14507): ... 11 more
I was told to put this in UI Thread but I don't know in which line of code the ui thread is. I simply put it next to other methods in the activity class file.
New code:
private class downloadWebPage extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
String resString = sb.toString();
is.close();
File file = new File(Environment.getExternalStorageDirectory().toString() + "/Android/data/com.whizzapps.stpsurniki/" + fileName + ".html");
file.createNewFile();
FileOutputStream f1 = new FileOutputStream(file, false);
PrintStream p = new PrintStream(f1);
p.print(resString);
p.close();
f1.close();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
The exception clearly indicates android.os.NetworkOnMainThreadException, which means you should always make Network call only in a seperate thread.
Solution: Create a new thread, and do Network call.
You can use AsyncTask, The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread from Android documentation
See the android link for more information.
Read the documentation about AsyncTask carefully.
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation
In your case, you should use Params to send parameter to the method (e.g url and filename)
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