I have a TO DO List, and when I check the checkbox in one Activity I want the CheckBox and the text that is next to the Checkbox to go to another Activity. this is my Adapter:
public class MyItemAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MyItemAdapter(Context context, String[] values) {
super(context, R.layout.item_list, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_list, parent, false);
CheckBox textView = (CheckBox) rowView.findViewById(R.id.checkBox1);
textView.setText(values[position]);
return rowView;
}
public static SparseBooleanArray getCheckedItemPositions() {
// TODO Auto-generated method stub
return null;
}
public static void remove(Object pos) {
// TODO Auto-generated method stub
}
public void changeData(String[] items) {
// TODO Auto-generated method stub
}
public static void setAdapter(MyItemAdapter mAdapter) {
// TODO Auto-generated method stub
}
This is my First Activity code:
final CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FinishedItems.class);
intent.putExtra("check", items);
Bundle extras = new Bundle();
extras.putString("status", "Data Recived");
intent.putExtras(extras);
startActivity(intent);
}
});
}
This is my Second Activity code:
Intent intent = getIntent();
String check = intent.getStringExtra("check");
((CheckBox)findViewById(R.id.checkBox1)).setText(check);
Bundle bundle = intent.getExtras();
String status = bundle.getString("status");
Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
toast.show();
And Finaly this is my Log cat:
02-18 10:33:24.779: D/AndroidRuntime(1575): Shutting down VM
02-18 10:33:24.779: W/dalvikvm(1575): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-18 10:33:24.789: E/AndroidRuntime(1575): FATAL EXCEPTION: main
02-18 10:33:24.789: E/AndroidRuntime(1575): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Stanton.quicktodolist/com.Stanton.quicktodolist.MainActivity}: java.lang.NullPointerException
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.os.Handler.dispatchMessage(Handler.java:99)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.os.Looper.loop(Looper.java:130)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-18 10:33:24.789: E/AndroidRuntime(1575): at java.lang.reflect.Method.invokeNative(Native Method)
02-18 10:33:24.789: E/AndroidRuntime(1575): at java.lang.reflect.Method.invoke(Method.java:507)
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 10:33:24.789: E/AndroidRuntime(1575): at dalvik.system.NativeStart.main(Native Method)
02-18 10:33:24.789: E/AndroidRuntime(1575): Caused by: java.lang.NullPointerException
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.Stanton.quicktodolist.MainActivity.onCreate(MainActivity.java:70)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-18 10:33:24.789: E/AndroidRuntime(1575): ... 11 more
Please Help me
This line of your stacktrace
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.Stanton.quicktodolist.MainActivity.onCreate(MainActivity.java:70)
points you to the error. Line 70 in the MainActivity causes a null pointer. It is often helpful to study and understand stacktraces. If you cannot figure it out yourself, show us the onCreate method of the MainActivity.
I believe that you replace the intent extra by the bundle extra just try this code and let me know pelase
final CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FinishedItems.class);
intent.putExtra("check", items);
//Bundle extras = new Bundle();
// extras.putString("status", "Data Recived");
intent.putExtras("status", "Data Recived");
startActivity(intent);
}
});
}
And the int the second activity
Intent intent = getIntent();
String check = intent.getStringExtra("check");
((CheckBox)findViewById(R.id.checkBox1)).setText(check);
// Bundle bundle = intent.getExtras();
String status = intent.getStringExtra("status");
Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
toast.show();
Related
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtUserName = (EditText)findViewById(R.id.editText1);
final EditText txtPassword = (EditText)findViewById(R.id.editText2);
Button btnLogin = (Button)findViewById(R.id.button1);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
String foo = new String("131031001");
String foo2 = new String("131031002");
String foo3 = new String("131031003");
String foo4 = new String("131031004");
String foo5 = new String("131031005");
try{
if(username.length() > 0 && password.length() >0) {
DBUserAdapter dbUser = new DBUserAdapter(MainActivity.this);
dbUser.open();
dbUser.AddUser();
if(dbUser.Login(username, password))
{
Toast.makeText(MainActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
if(username.equals(foo))
{
Intent nextActivity2 = new Intent(getApplicationContext(),SecondActivity.class);
nextActivity2.putExtra("Second",username);
startActivity(nextActivity2);
}
else if(username.equals(foo2)) {
Intent nextActivity3 = new Intent(getBaseContext(),ThirdActivity.class);
nextActivity3.putExtra("Third",username);
startActivity(nextActivity3);
}
else if(username.equals(foo3))
{
Intent nextActivity4 = new Intent(getBaseContext(),FourthActivity.class);
nextActivity4.putExtra("Fourth",username);
startActivity(nextActivity4);
}
else if(username.equals(foo4)) {
Intent nextActivity5 = new Intent(getBaseContext(),FifthActivity.class);
nextActivity5.putExtra("Fifth",username);
startActivity(nextActivity5);
}
else if(username.equals(foo5)) {
Intent nextActivity6 = new Intent(getBaseContext(),SixthActivity.class);
nextActivity6.putExtra("Sixth",username);
startActivity(nextActivity6);
}
else {
Toast.makeText(MainActivity.this,"Result does not exist! Try later!!", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(MainActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e) {
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
Button btreg = (Button)findViewById(R.id.button2);
btreg.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent nextActivity = new Intent(getApplicationContext(),Register.class);
startActivity(nextActivity);
}
});
}
}
SecondActivity.java
public class SecondActivity extends Activity {
Intent intent = getIntent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
}
}
All other activities are coded similar to the above.
Here is my logcat.
10-28 14:53:10.688: E/AndroidRuntime(1196): Process: com.skcetresults, PID: 1196
10-28 14:53:10.688: E/AndroidRuntime(1196): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.skcetresults/com.skcetresults.SecondActivity}: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.access$700(ActivityThread.java:135)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Looper.loop(Looper.java:137)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.main(ActivityThread.java:4998)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invoke(Method.java:515)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
10-28 14:53:10.688: E/AndroidRuntime(1196): at dalvik.system.NativeStart.main(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): Caused by: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.skcetresults.SecondActivity.onCreate(SecondActivity.java:15)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Activity.performCreate(Activity.java:5243)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
10-28 14:53:10.688: E/AndroidRuntime(1196): ... 11 more
With just two intents the code worked fine, but when I'm comparing the value with strings, the app crashes, I don't know where the bug is.
Instead of getBaseContext() and getApplicationContext(), use MainActivity.this as context, will work everywhere.
You should put it like this
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Intent i = getIntent();
}
}
If the extra data are strings you can get it like this:
String nameString = i.getStringExtra("nameExtra");
You can't use getIntent() before onCreate(), there's simply no Intent available at that point.
In your code, I suspect that you are trying to get StringExtras from Intent, But as intent is null, it is throwing NullPointerException.
In your Second Activity you can use getIntent() in onCreate() method.
public class SecondActivity extends Activity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
intent = getIntent();
String userName = intent.getStringExtra("Second");
...
}
}
Use little pieces of code checking, to ensure your intent behaves properly. For example, you could surround your getIntent code with an if statement. For which proper method to call, you have to wander around a bit, as this depends on what you want your app to do. Fortunately, Eclipse delivers you all the related documentation, when you write down some piece of Android resources, e.g. Intent.
I would like to update my Listview in a fragmen in a onPostExecute() separate class.
The first initialization of the the Listview doas work, but wehe I call createList() again, the App crashes (NullPointerException)
Any Idea?
Main_Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragmentView = inflater.inflate(R.layout.main_fragment, container, false);
StartSocketService = (Button) fragmentView.findViewById(R.id.start_socketservice);
StartSocketService.setOnClickListener(this);
StopSocketService = (Button) fragmentView.findViewById(R.id.stop_socketservice);
StopSocketService.setOnClickListener(this);
listview = (ListView) fragmentView.findViewById(R.id.listView1);
createList();
return fragmentView;
}
public void createList(){
//Reading Server IPs from SharedPreferences and put them to ListView
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
for (int i = 0; i < 255; i++) {
if ((settings.getString("Server"+i,null)) != null) {
serverList.add(settings.getString("Server"+i, null));
Log.v("Reading IP: " +settings.getString("Server"+i, null), " from SraredPreferrences at pos.: "+i );
}
}
//Initializing listView
final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, serverList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0).withEndAction(new Runnable() {
#Override
public void run() {
serverList.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
Some class:
async_cient = new AsyncTask<Void, Void, Void>() {
...
protected void onPostExecute(Void result) {
Toast.makeText(mContext, "Scan Finished", Toast.LENGTH_SHORT).show();
Main_Fragment cList = new Main_Fragment();
cList.createList();
super.onPostExecute(result);
}
};
Log:
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control D/AndroidRuntime﹕ Shutting down VM
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41549ba8)
07-29 14:42:46.438 3382-3382/de.liquidbeam.LED.control E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.liquidbeam.LED.control, PID: 3382
java.lang.NullPointerException
at de.liquidbeam.LED.control.fragments.Main_Fragment.createList(Main_Fragment.java:56)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:94)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:57)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
07-29 14:47:46.591 3382-3382/de.liquidbeam.LED.control I/Process﹕ Sending signal. PID: 3382 SIG: 9
Lines:
56 : SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
94 : cList.createList();
57: async_cient = new AsyncTask<Void, Void, Void>() {
You creating a new instance of your fragment with no context (activity) to run in. So
the line
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
Tries to get his activity but there is no activity where the fragment lives in ;)
I have spinner in Activity and edittext's. When i run the app I'm getting warning of nullPointerException.I dosen't retrieve the SQLite data in edit text in onCreate().Can someone help me.
Here is my code.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.delete_entry);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
spinner_searchByEmpName = (Spinner)findViewById(R.id.searchByEmpName);
loadSerachBYProject() ;
spinner_searchByEmpName.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
selectedEmployeeName = spinner_searchByEmpName.getSelectedItem().toString().trim();
System.out.println("selectedProjectName " + selectedEmployeeName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
etEmpName=(EditText)findViewById(R.id.Delete_editText_StaffEmployee_Name);
etDepartment=(EditText)findViewById(R.id.Delete_editText_Department);
etDesignation=(EditText)findViewById(R.id.Delete_editText_Designation);
try {
Cursor cursor = db.rawQuery("SELECT staff_employee_id, staff_emp_name, department, designation FROM employee_details WHERE staff_emp_name = ?",
new String[] { "" + selectedEmployeeName });
etEmpName.setText(cursor.getString(cursor
.getColumnIndex("staff_emp_name")));
etDepartment.setText(cursor.getString(cursor
.getColumnIndex("department")));
etDesignation.setText(cursor.getString(cursor
.getColumnIndex("designation")));
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void loadSerachBYProject()
{
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
// Spinner Drop down elements
List<String> projectsName = databaseHelper.getAllEmployeeName();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, projectsName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_searchByEmpName.setAdapter(dataAdapter);
}
}
Thanks in Advance.
Here is My Log cat error info
06-26 18:08:09.073: W/System.err(601): java.lang.NullPointerException
06-26 18:08:09.083: W/System.err(601): at com.employee_review.Update_Entry.onCreate(Update_Entry.java:68)
06-26 18:08:09.083: W/System.err(601): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-26 18:08:09.103: W/System.err(601): at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 18:08:09.103: W/System.err(601): at android.os.Looper.loop(Looper.java:123)
06-26 18:08:09.113: W/System.err(601): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-26 18:08:09.123: W/System.err(601): at java.lang.reflect.Method.invokeNative(Native Method)
06-26 18:08:09.133: W/System.err(601): at java.lang.reflect.Method.invoke(Method.java:507)
06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-26 18:08:09.133: W/System.err(601): at dalvik.system.NativeStart.main(Native Method)
Try this , i guess
if(cursor!=null){
etEmpName.setText(cursor.getString(cursor
.getColumnIndex("staff_emp_name")));
etDepartment.setText(cursor.getString(cursor
.getColumnIndex("department")));
etDesignation.setText(cursor.getString(cursor
.getColumnIndex("designation")));
}
db is never initialized. It must be initialized in onCreate(), as that's the first method that is run in an Activity. I see this:
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
I'm guessing you really should have this:
databaseHelper = new DatabaseHelper(this);
db=databaseHelper.getReadableDatabase();
I'm working on an android app that is supposed to load the gallery and grab an image and display it in an image view. I had it working but changed from Activities to Fragments to use the ViewPager and since then it has been crashing. I believe it is because I'm using a method intended for Activities on Fragments.
public class Fragment_1 extends Fragment {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Button buttonLoadImage = (Button) getView().findViewById(
R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.v("ButtonPress: ", "Pressed");
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Log.v("ButtonPress: ", "intent=" + i);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) getView().findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
The error I'm receiving is:
05-05 22:17:59.214: E/AndroidRuntime(32610): FATAL EXCEPTION: main
05-05 22:17:59.214: E/AndroidRuntime(32610): Process: com.example.hashtagged, PID: 32610
05-05 22:17:59.214: E/AndroidRuntime(32610): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hashtagged/com.example.hashtagged.Fragment_1}: java.lang.ClassCastException: com.example.hashtagged.Fragment_1 cannot be cast to android.app.Activity
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2131)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.access$800(ActivityThread.java:145)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.os.Handler.dispatchMessage(Handler.java:102)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.os.Looper.loop(Looper.java:136)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.main(ActivityThread.java:5142)
05-05 22:17:59.214: E/AndroidRuntime(32610): at java.lang.reflect.Method.invokeNative(Native Method)
05-05 22:17:59.214: E/AndroidRuntime(32610): at java.lang.reflect.Method.invoke(Method.java:515)
05-05 22:17:59.214: E/AndroidRuntime(32610): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
05-05 22:17:59.214: E/AndroidRuntime(32610): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
05-05 22:17:59.214: E/AndroidRuntime(32610): at dalvik.system.NativeStart.main(Native Method)
05-05 22:17:59.214: E/AndroidRuntime(32610): Caused by: java.lang.ClassCastException: com.example.hashtagged.Fragment_1 cannot be cast to android.app.Activity
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2122)
05-05 22:17:59.214: E/AndroidRuntime(32610): ... 11 more
Try inflate the View first on OnCreateView, like this:
private Button mButtonLoadImage;
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1, container, false);
mButtonLoadImage = (Button) view.findViewById(R.id.buttonLoadPicture);
return view;
}
And set onClickListener inside onViewCreated:
#Override public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mButtonLoadImage.setOnClickListener(onClickLoad);
}
//Good practice
private View.OnClickListener onClickLoad = new View.OnClickListener() {
#Override public void onClick(View view) {
//TODO action here
}
};
You are using onActivityResult() method of the activity class in your Fragment class. That is why you are getting this error. onActivityResult should be defined in your activity class of the your fragment class not on the fragment itself. See this link for how to do it.here
I'm trying to create a ListView with 2 TextViews and 1 Button. When the users click in the button the activity will finish(); and pass the result to another view. I followed this tutorial . But for some reason when i click to start that activity my application crashes! Here is the 3 files from my app that are relevant.
List Structure Data:
public class formulasListData {
private String formulasName;
private String formulasDefinition;
public formulasListData(String formulasName, String formulasDefinition) {
super();
this.formulasName = formulasName;
this.formulasDefinition = formulasDefinition;
}
public String getFormulasName() {
return formulasName;
}
public void setFormulasName(String formulasName) {
this.formulasName = formulasName;
}
public String getFormulasDefinition() {
return formulasDefinition;
}
public void setFormulasDefinition(String formulasDefinition) {
this.formulasDefinition = formulasDefinition;
}
}
The List Adapter:
public class formulasListAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<formulasListData> formulasList;
public formulasListAdapter(Context context, List<formulasListData> formulasList) {
this.context = context;
this.formulasList = formulasList;
}
#Override
public int getCount() {
return formulasList.size();
}
#Override
public Object getItem(int position) {
return formulasList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View rowView, ViewGroup parent) {
formulasListData entry = formulasList.get(position);
if(rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.formulas_row, null);
}
TextView formulasName = (TextView) rowView.findViewById(R.id.formulas_name);
formulasName.setText(entry.getFormulasName());
TextView formulasDefinition = (TextView) rowView.findViewById(R.id.formulas_definition);
formulasDefinition.setText(entry.getFormulasDefinition());
Button btnSelect = (Button) rowView.findViewById(R.id.selectFormula);
btnSelect.setFocusableInTouchMode(false);
btnSelect.setFocusable(false);
btnSelect.setOnClickListener(this);
btnSelect.setTag(entry);
return rowView;
}
#Override
public void onClick(View view) {
formulasListData entry = (formulasListData) view.getTag();
}
}
And the activity that should display the list.
public class FormulasList extends Activity {
private static final int FORMULA_0 = 0;
private static final int FORMULA_1 = 1;
private static final int FORMULA_2 = 2;
private static final int FORMULA_3 = 3;
private static final int FORMULA_4 = 4;
private static final int FORMULA_5 = 5;
private static final int FORMULA_6 = 6;
// private static final int FORMULA_7 = 7;
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
ListView formulasListView = (ListView) findViewById(R.id.formulas_list);
formulasListView.setClickable(true);
final List<formulasListData> formulasList = new ArrayList<formulasListData>();
final String[] formulasName = new String[] {"Circunference of a Circle:",
"Area of a Circle:",
"Volume of a Sphere:",
"Area Triangle:",
"Area Square:",
"Volume of a Cube:",
"Pithagorean Theorem:"};
final String[] formulasDefinition = new String[] {"2 × π × r",
"π × r²",
"(4/3) × π × r³",
"(b × h)/2",
"side²",
"side³",
"a² + b² = c²"};
// formulasList.add(new formulasListData(formulasName, formulasDefinition));
formulasList.add(new formulasListData(formulasName[0], formulasDefinition[0]));
formulasList.add(new formulasListData(formulasName[1], formulasDefinition[1]));
formulasList.add(new formulasListData(formulasName[2], formulasDefinition[2]));
formulasList.add(new formulasListData(formulasName[3], formulasDefinition[3]));
formulasList.add(new formulasListData(formulasName[4], formulasDefinition[4]));
formulasList.add(new formulasListData(formulasName[5], formulasDefinition[5]));
formulasList.add(new formulasListData(formulasName[6], formulasDefinition[6]));
SharedPreferences settings = getSharedPreferences(SettingsActivity.PREF_NAME, MODE_PRIVATE);
SettingsActivity.newTheme = settings.getInt("themeCustom", 0);
if(SettingsActivity.newTheme == SettingsActivity.THEME_DARK) {
setTheme(R.style.DarkTheme);
} else if(SettingsActivity.newTheme == SettingsActivity.THEME_LIGHT){
setTheme(R.style.LightTheme);
} else if(SettingsActivity.newTheme == SettingsActivity.THEME_COLORS) {
setTheme(R.style.ColorsTheme);
} else {
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_formulas);
formulasListAdapter adapter = new formulasListAdapter(this, formulasList);
formulasListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long index) {
Intent intent= getIntent();
Bundle b = new Bundle();
switch (position) {
case FORMULA_0:
b.putString("key0", formulasDefinition[0]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_1:
b.putString("key0", formulasDefinition[1]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_2:
b.putString("key0", formulasDefinition[2]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_3:
b.putString("key0", formulasDefinition[3]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_4:
b.putString("key0", formulasDefinition[4]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_5:
b.putString("key0", formulasDefinition[5]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_6:
b.putString("key0", formulasDefinition[6]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
default:
break;
}
}
});
formulasListView.setAdapter(adapter);
}
}
Thank you very much!!
EDIT: Here is the LogCat
05-01 20:06:54.436: D/libEGL(4820): loaded /system/lib/egl/libEGL_tegra.so
05-01 20:06:54.456: D/libEGL(4820): loaded /system/lib/egl/libGLESv1_CM_tegra.so
05-01 20:06:54.466: D/libEGL(4820): loaded /system/lib/egl/libGLESv2_tegra.so
05-01 20:06:54.486: D/OpenGLRenderer(4820): Enabling debug mode 0
05-01 20:06:54.536: D/dalvikvm(4820): GC_CONCURRENT freed 170K, 4% free 7509K/7808K, paused 4ms+10ms, total 38ms
05-01 20:06:59.976: D/AndroidRuntime(4820): Shutting down VM
05-01 20:06:59.976: W/dalvikvm(4820): threadid=1: thread exiting with uncaught exception (group=0x40cde930)
05-01 20:06:59.976: E/AndroidRuntime(4820): FATAL EXCEPTION: main
05-01 20:06:59.976: E/AndroidRuntime(4820): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabilheri.marcuscalculatorv2/com.gabilheri.marcuscalculatorv2.FormulasList}: java.lang.NullPointerException
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.os.Looper.loop(Looper.java:137)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 20:06:59.976: E/AndroidRuntime(4820): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 20:06:59.976: E/AndroidRuntime(4820): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 20:06:59.976: E/AndroidRuntime(4820): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 20:06:59.976: E/AndroidRuntime(4820): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 20:06:59.976: E/AndroidRuntime(4820): at dalvik.system.NativeStart.main(Native Method)
05-01 20:06:59.976: E/AndroidRuntime(4820): Caused by: java.lang.NullPointerException
05-01 20:06:59.976: E/AndroidRuntime(4820): at com.gabilheri.marcuscalculatorv2.FormulasList.onCreate(FormulasList.java:30)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.Activity.performCreate(Activity.java:5104)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-01 20:06:59.976: E/AndroidRuntime(4820): ... 11 more
Try moving
setContentView(R.layout.activity_formulas);
To the start of the method. Right after the super call.
You are trying to use gui controls before initializing the activity layout