I got problem with my first Android application. Just after running, my app crashes in emulator with "Unfortunately has stopped." message. I checked many threads on Stack and I read pretty much of official documentation and I really do not know what's a cause...
I use AVD with Android 4.4.2, API Level 19. CPU/ABI - ARM. Use Host GPU - checked (without this one emulator works very slowly).
My app should play a song after pressing the button. I would be really grateful for any ideas. Cheers.
Java file:
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
import android.media.MediaPlayer;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Button one = (Button) findViewById(R.id.button1);
final MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.elements6);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer1.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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();
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 {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
And XML file:
<?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/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Errors:
05-14 17:29:21.740: D/AndroidRuntime(1145): Shutting down VM
05-14 17:29:21.740: W/dalvikvm(1145): threadid=1: thread exiting with uncaught exception (group=0xb2abcba8)
05-14 17:29:21.750: E/AndroidRuntime(1145): FATAL EXCEPTION: main
05-14 17:29:21.750: E/AndroidRuntime(1145): Process: com.example.beatzlooper, PID: 1145
05-14 17:29:21.750: E/AndroidRuntime(1145): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.beatzlooper/com.example.beatzlooper.MainActivity}: java.lang.NullPointerException
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.os.Handler.dispatchMessage(Handler.java:102)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.os.Looper.loop(Looper.java:136)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-14 17:29:21.750: E/AndroidRuntime(1145): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 17:29:21.750: E/AndroidRuntime(1145): at java.lang.reflect.Method.invoke(Method.java:515)
05-14 17:29:21.750: E/AndroidRuntime(1145): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-14 17:29:21.750: E/AndroidRuntime(1145): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-14 17:29:21.750: E/AndroidRuntime(1145): at dalvik.system.NativeStart.main(Native Method)
05-14 17:29:21.750: E/AndroidRuntime(1145): Caused by: java.lang.NullPointerException
05-14 17:29:21.750: E/AndroidRuntime(1145): at com.example.beatzlooper.MainActivity.onCreate(MainActivity.java:31)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.Activity.performCreate(Activity.java:5231)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-14 17:29:21.750: E/AndroidRuntime(1145): ... 11 more
You are working with fragments.
The Fragment cannot be added to the R.id.container View because it doesn't exists.
Just delete the whole if-clause in the onCreate() and also delete the Placeholder Class you don't need it actually.
Comment this code
/*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}*/
Related
I am getting a NullPointerException. Below you can find my Logcat and the relevant code.
Logcat:
12-23 00:17:35.330: E/AndroidRuntime(2019): FATAL EXCEPTION: main
12-23 00:17:35.330: E/AndroidRuntime(2019): Process: com.android.timesheet, PID: 2019
12-23 00:17:35.330: E/AndroidRuntime(2019): java.lang.NullPointerException
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.timesheet.adapter.CustomCursorAdapter$1.onClick(CustomCursorAdapter.java:54)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View.performClick(View.java:4438)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View$PerformClick.run(View.java:18422)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.handleCallback(Handler.java:733)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.dispatchMessage(Handler.java:95)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Looper.loop(Looper.java:136)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.app.ActivityThread.main(ActivityThread.java:5017)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invokeNative(Native Method)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invoke(Method.java:515)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-23 00:17:35.330: E/AndroidRuntime(2019): at dalvik.system.NativeStart.main(Native Method)
CustomCursorAdapter.java:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.android.timesheet.ModifyMember;
import com.android.timesheet.R;
public class CustomCursorAdapter extends CursorAdapter {
Button delete_btn;
TextView memID_tv, memName_tv;
#SuppressWarnings("deprecation")
public CustomCursorAdapter(Activity context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
memID_tv = (TextView)v.findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
String memberID_val = memID_tv.getText().toString();; ---->54th Line
String memberName_val = memName_tv.getText().toString();
Intent i = new Intent(context,
ModifyMember.class);
i.putExtra("memberName", memberName_val);
i.putExtra("memberID", memberID_val);
((Activity)context).startActivity(i);
}
});
}
}
I am using a delete button to delete all the listview row items. At that point I am getting the NullPointerException.
Use view(view of row) instead of v parameter of onClick method which is view of Button :
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setTag(view);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowview=(View)v.getTag();
memID_tv = (TextView)rowview.findViewById(R.id.member_id);
memName_tv = (TextView)rowview.findViewById(R.id.member_name);
}
});
Use view instead of v
memID_tv = (TextView)view.findViewById(R.id.member_id);
In bindview try this-
if (view == null) {
view = inflater.inflate(R.layout.single_row_item, parent, null);
}
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
.
.
.
you are getting the view from clicked view, but you have to get the views from the root view.
memID_tv = (TextView)v. findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
change these lines into this:
memID_tv = (TextView)view. findViewById(R.id.member_id);
memName_tv = (TextView)view.findViewById(R.id.member_name);
Here is my LogCat...
Pls explain it for a noob, this is my first app program... But i need it for my Homework...Pls help me i need to get the echo of a php script and handle this data
05-14 14:03:22.268: E/AndroidRuntime(4674): FATAL EXCEPTION: main
05-14 14:03:22.268: E/AndroidRuntime(4674): java.lang.IllegalStateException: Could not execute method of the activity
05-14 14:03:22.268: E/AndroidRuntime(4674): at android.view.View$1.onClick(View.java:3063)
05-14 14:03:22.268: E/AndroidRuntime(4674): at android.view.View.performClick(View.java:3534)
05-14 14:03:22.268: E/AndroidRuntime(4674): at android.view.View$PerformClick.run(View.java:14263)
05-14 14:03:22.268: E/AndroidRuntime(4674): at android.os.Handler.handleCallback(Handler.java:605)
05-14 14:03:22.268: E/AndroidRuntime(4674): at android.os.Handler.dispatchMessage(Handler.java:92)
05-14 14:03:22.268: E/AndroidRuntime(4674): at android.os.Looper.loop(Looper.java:137)
05-14 14:03:22.268: E/AndroidRuntime(4674): at android.app.ActivityThread.main(ActivityThread.java:4441)
05-14 14:03:22.268: E/AndroidRuntime(4674): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 14:03:22.268: E/AndroidRuntime(4674): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 14:03:22.268: E/AndroidRuntime(4674): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-14 14:03:22.268: E/AndroidRuntime(4674): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-14 14:03:22.268: E/AndroidRuntime(4674): at dalvik.system.NativeStart.main(Native Method)
05-14 14:03:22.268: E/AndroidRuntime(4674): Caused by: java.lang.reflect.InvocationTargetException
05-14 14:03:22.268: E/AndroidRuntime(4674): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 14:03:22.268: E/AndroidRuntime(4674): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 14:03:22.268: E/AndroidRuntime(4674): at android.view.View$1.onClick(View.java:3058)
05-14 14:03:22.268: E/AndroidRuntime(4674): ... 11 more
05-14 14:03:22.268: E/AndroidRuntime(4674): Caused by: android.os.NetworkOnMainThreadException
05-14 14:03:22.268: E/AndroidRuntime(4674): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1108)
05-14 14:03:22.268: E/AndroidRuntime(4674): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
05-14 14:03:22.268: E/AndroidRuntime(4674): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
05-14 14:03:22.268: E/AndroidRuntime(4674): at java.net.InetAddress.getAllByName(InetAddress.java:220)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
05-14 14:03:22.268: E/AndroidRuntime(4674): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
05-14 14:03:22.268: E/AndroidRuntime(4674): at com.me.bittwaldstream.MainActivity.sendLogin(MainActivity.java:163)
05-14 14:03:22.268: E/AndroidRuntime(4674): ... 14 more
I dont know what to do... Im confused... This is my first Programm
with Android and Java but i need it for my homework...
(I know it will look like shit :))
Here is my full ActivityMain.java
package com.me.bittwaldstream;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.client.ClientProtocolException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new LoginFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class LoginFragment extends Fragment {
public LoginFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
public static class WaitFragment extends Fragment {
public WaitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.waiting_main, container, false);
return rootView;
}
}
public static class StreamFragment extends Fragment {
public StreamFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.videostream_main, container, false);
return rootView;
}
}
private static String readStream(InputStream is) {
final String TAG = "Stream";
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG, "IOException", e);
} finally {
try {
is.close();
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
}
return sb.toString();
}
//App beenden
public void abortApp(View v) {
finish();
}
//Login prüfen
public void sendLogin(View v) {
/*getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new WaitFragment())
.commit();*/
EditText username;
EditText passwort;
String result = "";
username = (EditText) findViewById(R.id.editTextUsername);
passwort = (EditText) findViewById(R.id.editTextPasswort);
if(username.getText().toString().trim().length() <= 0)
{
Toast.makeText(this, "Bitte geben Sie einen Usernamen an", Toast.LENGTH_LONG).show();
}
if(passwort.getText().toString().trim().length() <= 0)
{
Toast.makeText(this, "Bitte geben Sie ihr Passwort an", Toast.LENGTH_LONG).show();
}
URL url;
try {
url = new URL("http://shop.kokakukidotai.cf/echotest.php");
HttpURLConnection mUrlConnection = (HttpURLConnection) url.openConnection();
mUrlConnection.setDoInput(true);
InputStream is = new BufferedInputStream(mUrlConnection.getInputStream());
result = readStream(is);
} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
}
if(result == "allow")
{
Toast.makeText(this, "Login erfolgreich", Toast.LENGTH_LONG).show();
}
}
public void acceptRequest(View v) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new StreamFragment())
.commit();
}
public void overjump(View v) {
Button AcceptEvent;
ProgressBar Wait;
TextView Message;
AcceptEvent = (Button) findViewById(R.id.buttonAccept);
Wait = (ProgressBar) findViewById(R.id.progressBarWait);
Message = (TextView) findViewById(R.id.textViewWaiting);
Wait.setVisibility(View.GONE);
AcceptEvent.setVisibility(View.VISIBLE);
Message.setText(R.string.accept_event);
}
}
Here are my Mainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.me.bittwaldstream"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.me.bittwaldstream.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You are throwing a NetworkOnMainThreadException by performing network operations on your main Activity.
This is in place since Ice Cream Sandwitch.
Use an AsyncTask, Service, Handler, or in general, a background Thread to perform those operations.
I just started learning Android programming and have run into trouble. I'm using the book "Android Programming The Big Nerd Ranch Guide". My IDE is Eclipse and Genymotion to emulate the app. Here's the logcat:
04-13 00:19:48.065: D/dalvikvm(1256): Late-enabling CheckJNI
04-13 00:19:48.781: D/AndroidRuntime(1256): Shutting down VM
04-13 00:19:48.785: W/dalvikvm(1256): threadid=1: thread exiting with uncaught exception (group=0xa4d8ab20)
04-13 00:19:48.785: E/AndroidRuntime(1256): FATAL EXCEPTION: main
04-13 00:19:48.785: E/AndroidRuntime(1256): Process: com.bignerdranch.android.geoquiz, PID: 1256
04-13 00:19:48.785: E/AndroidRuntime(1256): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.geoquiz/com.bignerdranch.android.geoquiz.QuizActivity}: java.lang.NullPointerException
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.os.Handler.dispatchMessage(Handler.java:102)
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.os.Looper.loop(Looper.java:136)
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-13 00:19:48.785: E/AndroidRuntime(1256): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 00:19:48.785: E/AndroidRuntime(1256): at java.lang.reflect.Method.invoke(Method.java:515)
04-13 00:19:48.785: E/AndroidRuntime(1256): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-13 00:19:48.785: E/AndroidRuntime(1256): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-13 00:19:48.785: E/AndroidRuntime(1256): at dalvik.system.NativeStart.main(Native Method)
04-13 00:19:48.785: E/AndroidRuntime(1256): Caused by: java.lang.NullPointerException
04-13 00:19:48.785: E/AndroidRuntime(1256): at com.bignerdranch.android.geoquiz.QuizActivity.onCreate(QuizActivity.java:30)
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.app.Activity.performCreate(Activity.java:5231)
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-13 00:19:48.785: E/AndroidRuntime(1256): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-13 00:19:48.785: E/AndroidRuntime(1256): ... 11 more
04-13 00:19:56.345: I/Process(1256): Sending signal. PID: 1256 SIG: 9
Here's the fragment_quiz.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
android:text="#string/question_text" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/true_button" />
<Button
android:id="#+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/false_button" />
</LinearLayout>
</LinearLayout>
The QuizActivity.java file (most of the code imported by Eclipse):
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton;
private Button mFalseButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this, R.string.incorrect_toast, Toast.LENGTH_SHORT)
.show();
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT)
.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, menu);
return true;
}
#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();
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 {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_quiz, container,
false);
return rootView;
}
}
}
What am I doing wrong?
Put your layout definitions in the PlaceholderFragment class. For the findViewById, use rootView.findViewById. For the context, use getActivity().
Why does this work? There are actually 2 independent layouts shown as one in your screen. The master one shows everything, including a fragment. A Fragment is basically a self-contained mini activity, very useful in Tablet development, and mildly useful even just for a phone type device. Your layouts are in the fragment_quiz xml file, which is only inflated inside the fragment, in the onCreateView statement. So long as you use the findViewById after it's been inflated, you'll be fine.
MainActivity.java
package com.example.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;
import android.content.Intent;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
DisplayMessageActivity.java
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#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();
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 {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
Error Log
04-10 01:37:00.460: W/dalvikvm(1650): threadid=1: thread exiting with uncaught exception (group=0xb3aaeba8)
04-10 01:37:00.520: E/AndroidRuntime(1650): FATAL EXCEPTION: main
04-10 01:37:00.520: E/AndroidRuntime(1650): Process: com.example.myfirstapp, PID: 1650
04-10 01:37:00.520: E/AndroidRuntime(1650): java.lang.IllegalStateException: Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.MainActivity for onClick handler on view class android.widget.Button
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View$1.onClick(View.java:3810)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View.performClick(View.java:4438)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View$PerformClick.run(View.java:18422)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.os.Handler.handleCallback(Handler.java:733)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.os.Handler.dispatchMessage(Handler.java:95)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.os.Looper.loop(Looper.java:136)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.reflect.Method.invokeNative(Native Method)
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.reflect.Method.invoke(Method.java:515)
04-10 01:37:00.520: E/AndroidRuntime(1650): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-10 01:37:00.520: E/AndroidRuntime(1650): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-10 01:37:00.520: E/AndroidRuntime(1650): at dalvik.system.NativeStart.main(Native Method)
04-10 01:37:00.520: E/AndroidRuntime(1650): Caused by: java.lang.NoSuchMethodException: sendMessage [class android.view.View]
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.Class.getConstructorOrMethod(Class.java:472)
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.Class.getMethod(Class.java:857)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View$1.onClick(View.java:3803)
04-10 01:37:00.520: E/AndroidRuntime(1650): ... 11 more
04-10 01:37:04.820: I/Process(1650): Sending signal. PID: 1650 SIG: 9
I've tried to look at other questions answered similar to mine, but I can't find an answer that seems to help my situation. Can anyone help?
I was struggling with a similar error following the android tutorial
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myfirstapp, PID: 18300
java.lang.IllegalStateException: Could not find method sendMessage (MainActivity)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20909)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5944)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
but in my case the WYSIWYG editor (IntelliJ w/Android Studio plugin) ended up populating the onClick property in activity_main.xml with some extra junk about MainActivity:
android:onClick="sendMessage (MainActivity)"
So I deleted " (MainActivity)" and it stopped crashing. I see this is different from your problem as your xml file already seems correct with android:onClick="sendMessage". But wanted to add it here for any others struggling with what I saw. This was the closest post to the issue I was seeing. I'm just getting started and this was killing me, so hope it helps someone else.
The problem is the onClick property in one of your Button tags:
android:onClick="sendMessage" />
Just make sure you have a method sendMessage(View) in your Activity.
It is because you need to implement implements android.view.View.OnClickListener in your class, therefore add the correct imports i.e. import android.view.View.
I try to change 3 textviews in a class called UserProfile() calling the method update() from the class UpdateProfile(), the class UserProfile do something like this:
package com.safm;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class UserProfile extends Activity {
TextView username, usersurname, useremail;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
username = (TextView) findViewById(R.id.username);
usersurname = (TextView) findViewById(R.id.usersurname);
useremail = (TextView) findViewById(R.id.useremail);
}
public void updateButton(View view){
Intent i = new Intent(this, UpdateProfile.class);
startActivity(i);
}
public void update(String nname, String nusername, String nemail){
System.out.println("2");
System.out.println(nname);
username.setText(nname);
usersurname.setText(nusername);
useremail.setText(nemail);
System.out.println("3");
}
}
The updateButton method invoke the UpdateProfile class:
package com.safm;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateProfile extends Activity {
EditText newusernametxt, newsurnametxt, newemailtxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actualizarperfil);
newusernametxt = (EditText) findViewById(R.id.newusernametxt);
newsurnametxt = (EditText) findViewById(R.id.newsurnametxt );
newemailtxt = (EditText) findViewById(R.id.newemailtxt );
}
public void updateInfo(View view){
String nname = newusernametxt .getText().toString();
String nsurname = newsurnametxt .getText().toString();
String nemail = newemailtxt .getText().toString();
if(nname.compareTo("") != 0 && nsurname.compareTo("") != 0 && nemail.compareTo("") != 0){
UserProfile profile = new UserProfile();
System.out.println("1");
profile.update(nname, nsurname, nemail);
System.out.println("4");
Toast.makeText(this, "Success, the profile has been updated", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "You can't empty fields", Toast.LENGTH_SHORT).show();
}
}
This is my logcat file, as you can see, the first 2 flags are printed correctly, the error is when I try to set another text on the TextView, but the value of the strings (nname, nsurname and nemail) are not empty cause also is printed in the console HELP!
05-14 21:43:31.140: I/System.out(878): 1
05-14 21:43:31.140: I/System.out(878): 2
05-14 21:43:31.150: I/System.out(878): TextEditValue
05-14 21:43:31.150: D/AndroidRuntime(878): Shutting down VM
05-14 21:43:31.150: W/dalvikvm(878): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-14 21:43:31.310: E/AndroidRuntime(878): FATAL EXCEPTION: main
05-14 21:43:31.310: E/AndroidRuntime(878): java.lang.IllegalStateException: Could not execute method of the activity
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View$1.onClick(View.java:3599)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View.performClick(View.java:4204)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View$PerformClick.run(View.java:17355)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.os.Handler.handleCallback(Handler.java:725)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:92)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:137)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 21:43:31.310: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-14 21:43:31.310: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-14 21:43:31.310: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
05-14 21:43:31.310: E/AndroidRuntime(878): Caused by: java.lang.reflect.InvocationTargetException
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View$1.onClick(View.java:3594)
05-14 21:43:31.310: E/AndroidRuntime(878): ... 11 more
05-14 21:43:31.310: E/AndroidRuntime(878): Caused by: java.lang.NullPointerException
05-14 21:43:31.310: E/AndroidRuntime(878): at com.safm.UserProfile.update(UserProfile.java:31)
05-14 21:43:31.310: E/AndroidRuntime(878): at com.safm.UserProfile.updateInfo(UpdateProfile.java:33)
05-14 21:43:31.310: E/AndroidRuntime(878): ... 14 more
NOTE: I've clean the project and defined the TextView in ProfileUser class and the TextEdit in UpdateProfile outside the onCreate method but doesn't work.
Thanks.
Activities in Android are separate containers, that are in no way allowed to directly touch eachother. This is because the application stack behind Android 'freezes' the activities when they are no longer on the foreground, and could even be swapped to hard storage to save on RAM at the operating system's discretion.
Your UserProfile encapsulation should just reload its data after the UpdateProfile activity is closed, or request communication back the proper way via startActivityForResult.
Your current implementation is technically incorrect from each perspective, since you're hardcoding the UpdateProfile activity to always be called from a UserProfile activity. What if some day you introduce a new menu option to call it directly from the home screen? Activities are always separate, and should not make such assumptions.