This question already has an answer here:
"Unfortunately, ... has stopped" when Downloading file in Android
(1 answer)
Closed 8 years ago.
Im making an app where the user has to download a file in order for the app to work.
I added a new Class called 'HTTPTest' which downloads the file. When I click on the button to download the file, it says "Unfortunately, ... has stopped.".
First, heres the Log:
Process: com.NautGames.xecta.app, PID: 2759
java.lang.IllegalStateException: Could not find a method onClick(View) in the activity class com.NautGames.xecta.app.MainActivity for onClick handler on view class android.widget.Button with id 'Button01'
at android.view.View$1.onClick(View.java:3810)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: onClick [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:857)
at android.view.View$1.onClick(View.java:3803)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Heres the HTTPTest Class:
package com.NautGames.xecta.app;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HTTPTest extends Activity {
String Path = Environment.getExternalStorageDirectory().getPath() + "/Download";
String dwnload_file_path = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/187259_10000060421658402_744490318028_q.jpg";
String dest_file_path = Path;
Button b1;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.Button01);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(HTTPTest.this, "", "Downloading file...", true);
new Thread(new Runnable() {
public void run() {
downloadFile(dwnload_file_path, dest_file_path);
}
}).start();
}
});
}
public void downloadFile(String url, String dest_file_path) {
try {
File dest_file = new File(dest_file_path);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
void hideProgressIndicator(){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
}
activity_main.xml:
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.NautGames.chatbot.app.MainActivity"
android:background="#drawable/oneiric640x960">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText1"
android:hint="Talk to Xecta"
android:layout_below="#+id/view"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_below="#+id/editText1"
android:onClick="buttonOnClick" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="File Download Demo from Coderzheaven \n\nFile to download : http://coderzheaven.com/sample_folder/sample_file.png \n\nSaved Path : sdcard/\n"
android:id="#+id/textView"
android:layout_below="#+id/button1"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="31dp" />
<Button
android:text="Download File"
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:onClick="onClick">
</Button>
</RelativeLayout>
MainActivity.java
package com.NautGames.xecta.app;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//Chat bot library
import org.alicebot.ab.Chat;
import org.alicebot.ab.Bot;
import android.view.View;
import android.widget.Button;
import android.os.Environment;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//EditText mEdit = (EditText)findViewById(R.id.editText1);
public void buttonOnClick(View v)
{
input = (TextView) findViewById(R.id.editText1);
String dbPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/Ab";
Button button=(Button) v;
//Creating bot
String botname="xecta";
String path= dbPath;
Bot xecta = new Bot(botname, path);
Chat chatSession = new Chat(xecta);
String request = input.getText().toString();
String response = chatSession.multisentenceRespond(request);
((Button) v).setText(response);
}
#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);
}
}
Please tell me how to fix this, Thanks.
as per this answer on your other question
you need to add an onClick(View view) method to your MainActivity
Related
I have a problem that I can not solve, the problem TabHost that crashes when apk run,I've been trying hard for this but still can not, please help.
activity_main.xml
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#android:id/tabs"
android:layout_gravity="bottom"></TabWidget>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom"
android:id="#android:id/tabcontent"></FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
MainActivity.java
package com.example.asus.smartcity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.widget.TabHost;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabhostku = (TabHost)findViewById(android.R.id.tabhost);
tabhostku.setup();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, MapActivity.class);
spec = tabhostku.newTabSpec("map");
spec.setIndicator("map",null);
spec.setContent(intent);
tabhostku.addTab(spec);
intent = new Intent().setClass(this, PlaceActivity.class);
spec = tabhostku.newTabSpec("place");
spec.setIndicator("place",null);
spec.setContent(intent);
tabhostku.addTab(spec);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MapActivity.java
import android.app.Activity;
import android.os.Bundle;
/**
* Created by Asus on 11-Nov-15.
*/
public class MapActivity extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
}
}
PlaceActivity.java
package com.example.asus.smartcity;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
/**
* Created by Asus on 11-Nov-15.
*/
public class PlaceActivity extends ListActivity {
String []placeku={"KBS","Surabaya Carnival","Kebun Bibit"};
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.place);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,placeku));
}
}
Logcat
11-11 12:51:22.153 19591-19591/? I/art﹕ Late-enabling -Xcheck:jni
11-11 12:51:22.223 19591-19591/com.example.asus.smartcity W/ResourceType﹕ For resource 0x01040529, entry index(1321) is beyond type entryCount(1)
11-11 12:51:22.287 19591-19591/com.example.asus.smartcity W/ResourceType﹕ For resource 0x0104007b, entry index(123) is beyond type entryCount(1)
11-11 12:51:22.288 19591-19591/com.example.asus.smartcity W/ResourceType﹕ For resource 0x01040077, entry index(119) is beyond type entryCount(1)
11-11 12:51:22.314 19591-19591/com.example.asus.smartcity W/ResourceType﹕ For resource 0x0104007b, entry index(123) is beyond type entryCount(1)
11-11 12:51:22.318 19591-19591/com.example.asus.smartcity D/AndroidRuntime﹕ Shutting down VM
11-11 12:51:22.320 19591-19591/com.example.asus.smartcity E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.asus.smartcity, PID: 19591
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asus.smartcity/com.example.asus.smartcity.MainActivity}: java.lang.IllegalStateException: Did you forget to call 'public void setup(LocalActivityManager activityGroup)'?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5371)
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:945)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Caused by: java.lang.IllegalStateException: Did you forget to call 'public void setup(LocalActivityManager activityGroup)'?
at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:754)
at android.widget.TabHost.setCurrentTab(TabHost.java:420)
at android.widget.TabHost.addTab(TabHost.java:247)
at com.example.asus.smartcity.MainActivity.onCreate(MainActivity.java:29)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5371)
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:945)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
11-11 12:51:25.717 19591-19591/com.example.asus.smartcity I/Process﹕ Sending signal. PID: 19591 SIG: 9
You have to change extends AppCompatActivity to ActivityGroup After that change
tabhostku.setup();
to
tabhostku.setup(this.getLocalActivityManager());
Try this,
Change,
tabhostku.setup();
to
mlam = new LocalActivityManager(this, false);
tabhostku.setup(mlam );
And in onPause and onResume add the following code.
#Override
public void onPause() {
super.onPause();
try {
mlam.dispatchPause(isFinishing());
} catch (Exception e) {}
}
#Override
public void onResume() {
super.onResume();
try {
mlam.dispatchResume();
} catch (Exception e) {}
}
I am attempting to implement a to-do list using listview and listview adapter but have run into several runtime exceptions that I can't overcome. Logcat says that I am trying to invoke findViewById on a null object reference (line 24 = private Spinner spinner_priority;). However, the id for the spinner is spinnerPriority and findViewById(R.id.spinnerPriority) is invoked correctly.
I haven't changed the default ToDoActivity.java implementation except for extending ToDoActivity from FragmentActivity instead of AppCombatActivity and importing android.support.v4.app.FragmentActivity instead of android.app.FragmentActivity.
Any insights as to why the app is crashing?
Logcat:
08-27 00:45:58.209 11873-11873/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.ttse.final_tse, PID: 11873
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ttse.final_tse/com.ttse.final_tse.ToDoActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:378)
at android.app.Activity.setContentView(Activity.java:2145)
at com.ttse.final_tse.ToDoActivity.onCreate(ToDoActivity.java:14)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v4.app.FragmentActivity.findViewById(int)' on a null object reference
at com.ttse.final_tse.ToDoActivityFragment.<init>(ToDoActivityFragment.java:24)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.support.v4.app.Fragment.instantiate(Fragment.java:421)
at android.support.v4.app.Fragment.instantiate(Fragment.java:396)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2162)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:300)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:378)
at android.app.Activity.setContentView(Activity.java:2145)
at com.ttse.final_tse.ToDoActivity.onCreate(ToDoActivity.java:14)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
ToDoActivity.java
package com.ttse.final_tse;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class ToDoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_to_do, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_to_do.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment"
android:name="com.ttse.final_tse.ToDoActivityFragment"
tools:layout="#layout/fragment_to_do"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
ToDoActivityFragment.java
package com.ttse.final_tse;
import android.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class ToDoActivityFragment extends Fragment {
private List<Task> list_tasks = new ArrayList<Task>();
private ArrayAdapter<Task> list_adapter = null;
private final EditText editText_title = (EditText)getActivity().findViewById(R.id.editTextTitle);
private Spinner spinner_priority;
private Button button_datepicker;
private final TextView textView_date = (TextView)getActivity().findViewById(R.id.textViewDate);
private EditText editText_shortDescr;
private Button button_save;
public ToDoActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_to_do, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// To-Do ListView
ListView list = (ListView)getActivity().findViewById(R.id.listViewToDo);
list_adapter = new ArrayAdapter<Task>(getActivity(), android.R.layout.simple_list_item_1, list_tasks);
list.setAdapter(list_adapter);
// Priority Spinner
spinner_priority = (Spinner)getActivity().findViewById(R.id.spinnerPriority);
ArrayAdapter<CharSequence> spinner_adapter = ArrayAdapter.createFromResource(getActivity(), R.array.priority_array, android.R.layout.simple_spinner_item);
spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_priority.setAdapter(spinner_adapter);
spinner_priority.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Datepicker Button
button_datepicker = (Button)getActivity().findViewById(R.id.buttonDatepicker);
button_datepicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog(v);
}
});
// Short Description EditText
editText_shortDescr = (EditText)getActivity().findViewById(R.id.editTextShortDescr);
// Save Button
button_save = (Button)getActivity().findViewById(R.id.buttonSave);
button_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(editText_title.getText()) || TextUtils.isEmpty(textView_date.getText())) {
Toast.makeText(getActivity(), "Please set to-do title and due date", Toast.LENGTH_SHORT).show();
return;
}
onSave();
}
});
}
private void showDatePickerDialog(View v) {
DialogFragment date_picker = new DatePickerFragment();
// show datepicker fragment on screen
date_picker.show(getActivity().getFragmentManager(), "datePicker");
}
private void onSave() {
Task task = new Task();
task.setTitle(editText_title.getText().toString());
task.setPriority(spinner_priority.getSelectedItem().toString());
task.setDueDate(textView_date.getText().toString());
task.setShortDescr(editText_shortDescr.getText().toString());
list_adapter.add(task);
list_adapter.notifyDataSetChanged();
}
}
fragment_to_do.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".ToDoActivityFragment">
<ListView
android:id="#+id/listViewToDo"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10">
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
android:layout_weight="7">
<EditText
android:id="#+id/editTextTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title..."/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:text="Priority Level:"
android:layout_marginTop="5dp"/>
<Spinner
android:id="#+id/spinnerPriority"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:spinnerMode="dropdown"
android:layout_marginTop="5dp"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:orientation="vertical">
<Button
android:id="#+id/buttonDatepicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/pick_date"/>
<TextView
android:id="#+id/textViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
</LinearLayout>
<EditText
android:id="#+id/editTextShortDescr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Short description..."
android:textSize="14sp"/>
<Button
android:id="#+id/buttonSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_save"
android:layout_gravity="center"/>
</LinearLayout>
</LinearLayout>
DatePickerFragment.java
package com.ttse.final_tse;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
TextView textView_date = (TextView)getActivity().findViewById(R.id.textViewDate);
textView_date.setText(new StringBuilder()
.append(month + 1).append("/").append(day).append("/")
.append(year));
}
}
Task.java
package com.ttse.final_tse;
public class Task {
private String mTitle;
private String mDueDate;
private String mPriority;
private String mShortDescr;
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public String getDueDate() {
return mDueDate;
}
public void setDueDate(String dueDate) {
mDueDate = dueDate;
}
public String getPriority() {
return mPriority;
}
public void setPriority(String priority) {
mPriority = priority;
}
public String getShortDescr() {
return mShortDescr;
}
public void setShortDescr(String shortDescr) {
mShortDescr = shortDescr;
}
}
update your code like this
private EditText editText_title ;
private TextView textView_date ;
initialize in onActivityCreated
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// To-Do ListView
editText_title = (EditText)getActivity().findViewById(R.id.editTextTitle);
textView_date = (TextView)getActivity().findViewById(R.id.textViewDate);
I'm trying to get the input value from EditText in SearchUser to query in SearchResult
Here is my Code for SearchUser :
package com.example.yearbookmuict9sec2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.EditText;
public class SearchUser extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_user);
addButtonListenerHomeButton();
addButtonListenerViewAll();
addButtonListenerSearchButton();
}
private void addButtonListenerSearchButton() {
// TODO Auto-generated method stub
Button button = (Button) findViewById(R.id.SearchButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtSearch;
String Answer;
edtSearch = (EditText)findViewById(R.id.answer);
Answer = edtSearch.getText().toString();
Intent goAnswer = new Intent(getApplicationContext(),SearchResult.class);
goAnswer.putExtra("Answer", Answer);
startActivity(goAnswer);
}
});
}
private void addButtonListenerViewAll() {
// TODO Auto-generated method stub
Button button = (Button) findViewById(R.id.viewALLBUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(SearchUser.this,ViewAll.class);
startActivity(i);
}
});
}
private void addButtonListenerHomeButton() {
// TODO Auto-generated method stub
ImageButton button = (ImageButton) findViewById(R.id.HomeButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(SearchUser.this,Home.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_user, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my activity_search_user :
<ScrollView
android:id="#+id/scrollView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/HomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/home1"
android:layout_alignTop="#+id/scrollView4"
android:background="#fffbf8f0"
android:src="#drawable/ic_home_black_24dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/home1"
android:layout_below="#+id/HomeButton"
android:text="Back Home" />
<Button
android:id="#+id/viewALLBUTTON"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/SearchButton"
android:layout_alignBottom="#+id/SearchButton"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/HomeButton"
android:background="#ffff6c41"
android:text="View All"
android:textColor="#ffffffff" />
<ImageView
android:id="#+id/home1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:src="#drawable/logo_180" />
<Button
android:id="#+id/SearchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/home1"
android:layout_below="#+id/home1"
android:layout_marginLeft="56dp"
android:layout_marginTop="47dp"
android:background="#ff606efd"
android:nestedScrollingEnabled="false"
android:text="Search"
android:textColor="#ffffffff" />
<EditText
android:id="#+id/answer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/viewALLBUTTON"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
Here is my code for SearchResult :
package com.example.yearbookmuict9sec2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class SearchResult extends Activity {
SQLiteDatabase mDb;
Database mHelper;
Cursor mCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
EditText txtAnswer;
Button btnBack;
String showAnswer;
txtAnswer = (EditText)findViewById(R.id.answer);
btnBack = (Button)findViewById(R.id.SearchButton);
showAnswer = getIntent().getStringExtra("Answer");
txtAnswer.setText(showAnswer);
ListView listView1 = (ListView)findViewById(R.id.listView1);
mHelper = new Database(this);
mDb = mHelper.getWritableDatabase();
mHelper.onUpgrade(mDb, 1, 1);
mCursor = mDb.rawQuery("SELECT " + Database.COL_StudentID + ", "
+ Database.COL_FNAME + ", " + Database.COL_LNAME+ ", "
+ Database.COL_NNAME + " FROM " + Database.TABLE_NAME +" WHERE "
+ Database.COL_StudentID + " = ?", new String[] {showAnswer});
ArrayList<String> dirArray = new ArrayList<String>();
mCursor.moveToFirst();
while ( !mCursor.isAfterLast() ){
dirArray.add("ID : " + mCursor.getString(mCursor.getColumnIndex(Database.COL_StudentID)) + "\n"
+ "Firstname : " + mCursor.getString(mCursor.getColumnIndex(Database.COL_FNAME)) + "\n"
+ "Lastname : " + mCursor.getString(mCursor.getColumnIndex(Database.COL_LNAME)) + "\n"
+ "Nickname : " + mCursor.getString(mCursor.getColumnIndex(Database.COL_NNAME)));
mCursor.moveToNext();
}
ArrayAdapter<String> adapterDir = new ArrayAdapter<String>(getApplicationContext()
, android.R.layout.simple_list_item_1, dirArray);
listView1.setAdapter(adapterDir);
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("First Line", "First line of text");
datum.put("Second Line","Second line of text");
data.add(datum);
SimpleAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2,
new String[] {"First Line", "Second Line" },
new int[] {android.R.id.text1, android.R.id.text2 });
}
public void onPause() {
super.onPause();
mHelper.close();
mDb.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_result, 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);
}
}
Here is my activity_search_result :
<Button
android:id="#+id/backToHome"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/listView1"
android:layout_toEndOf="#+id/imageView"
android:background="#ffafff9b"
android:text="Back to Home" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Student"
android:textColor="#FFFFFF"
android:textSize="40dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_margin="30dp"
android:cacheColorHint="#00000000" >
</ListView>
</RelativeLayout>
Here is my LogCat :
12-09 03:57:09.421: E/AndroidRuntime(4961): FATAL EXCEPTION: main
12-09 03:57:09.421: E/AndroidRuntime(4961): Process: com.example.yearbookmuict9sec2, PID: 4961
12-09 03:57:09.421: E/AndroidRuntime(4961): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.yearbookmuict9sec2/com.example.yearbookmuict9sec2.SearchResult}: java.lang.NullPointerException
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.access$800(ActivityThread.java:135)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.os.Handler.dispatchMessage(Handler.java:102)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.os.Looper.loop(Looper.java:136)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.main(ActivityThread.java:5001)
12-09 03:57:09.421: E/AndroidRuntime(4961): at java.lang.reflect.Method.invokeNative(Native Method)
12-09 03:57:09.421: E/AndroidRuntime(4961): at java.lang.reflect.Method.invoke(Method.java:515)
12-09 03:57:09.421: E/AndroidRuntime(4961): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-09 03:57:09.421: E/AndroidRuntime(4961): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-09 03:57:09.421: E/AndroidRuntime(4961): at dalvik.system.NativeStart.main(Native Method)
12-09 03:57:09.421: E/AndroidRuntime(4961): Caused by: java.lang.NullPointerException
12-09 03:57:09.421: E/AndroidRuntime(4961): at com.example.yearbookmuict9sec2.SearchResult.onCreate(SearchResult.java:39)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.Activity.performCreate(Activity.java:5231)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
12-09 03:57:09.421: E/AndroidRuntime(4961): ... 11 more
Help me please.
What i have to do to fix this problem? I'm new here.
The problem is sourced on line 39 in SearchResult.java. You can see this in the LogCat on the line after the one that starts with Caused by: java.lang.NullPointerException.
txtAnswer is not a valid id for an EditText object in your activity_search_result.xml, so it returned null on line 35 when you searched for it. You cannot call .setText() on a null object.
txtAnswer is null. This is because it is not in the activity's view. Your activity loads its view as follows:
setContentView(R.layout.activity_search_result);
Yet the element with ID answer id not defined in activity_search_result.xml. It is defined in activity_search_user.xml.
So your problem is either:
a) You are loading the wrong view for your activity OR
b) You forgot to add the EditText with ID answer to your view (activity_search_result.xml)
Edit - looking at your code, I think it is likely that option is is the problem. So to fix this, change
setContentView(R.layout.activity_search_result);
to
setContentView(R.layout.activity_search_user);
You activity_search_result.xml does not contain any view that you have specified in your activity. You may have to pass right layout xml file in setContentView or change id of EditText and Button.
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I am having trouble finding the source of the crash in my application. I've done a clean/build. I'm very new to Android dev so I'm still learning. From looking at the logcat, I think there maybe some null error exception that might have something to do with the calculate function. Any help or guidance is appreciated.
The java code:
package com.example.rectangle;
import java.text.DecimalFormat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.os.Build;
public class MainActivity extends ActionBarActivity implements OnEditorActionListener {
//graphical variables
private EditText widthInput;
private EditText heightInput;
private TextView areaOutput;
private TextView perimeterOutput;
private Button calculateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assign ids to graphical variables
widthInput = (EditText) findViewById(R.id.widthEditText);
heightInput = (EditText) findViewById(R.id.heightEditText);
areaOutput = (TextView) findViewById(R.id.areaOutput);
perimeterOutput = (TextView) findViewById(R.id.perimterOutput);
calculateButton = (Button) findViewById(R.id.calculateButton);
widthInput.setOnEditorActionListener(this);
heightInput.setOnEditorActionListener(this);
//calculate and display
calculateAreaAndPerimeter();
}
//hide keyboard
//source: http://stackoverflow.com/questions/8697499/hide-keyboard-when-user-taps-anywhere-else-on-the-screen-in-android
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#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;
}
}
//display
public void display(String area, String perimeter)
{
areaOutput.setText(area);
perimeterOutput.setText(perimeter);
}
//algorithms
private void calculateAreaAndPerimeter()
{
//get width and height
String widthInputString = widthInput.getText().toString();
String heightInputString = heightInput.getText().toString();
float width = Float.parseFloat(widthInputString);
float height = Float.parseFloat(heightInputString);
//calculate and display
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
float area;
area = width * height;
String areaString = (df.format(area)) + "";
float perimeter;
perimeter = (width * 2) + (height * 2);
String perimeterString = (df.format(perimeter)) + "";
display(areaString, perimeterString);
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
calculateAreaAndPerimeter();
return false;
}
}
The logcat:
11-12 13:05:14.049: E/AndroidRuntime(10535): FATAL EXCEPTION: main
11-12 13:05:14.049: E/AndroidRuntime(10535): Process: com.example.rectangle, PID: 10535
11-12 13:05:14.049: E/AndroidRuntime(10535): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rectangle/com.example.rectangle.MainActivity}: java.lang.NullPointerException
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.access$800(ActivityThread.java:139)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.os.Handler.dispatchMessage(Handler.java:102)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.os.Looper.loop(Looper.java:136)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.main(ActivityThread.java:5086)
11-12 13:05:14.049: E/AndroidRuntime(10535): at java.lang.reflect.Method.invokeNative(Native Method)
11-12 13:05:14.049: E/AndroidRuntime(10535): at java.lang.reflect.Method.invoke(Method.java:515)
11-12 13:05:14.049: E/AndroidRuntime(10535): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
11-12 13:05:14.049: E/AndroidRuntime(10535): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
11-12 13:05:14.049: E/AndroidRuntime(10535): at dalvik.system.NativeStart.main(Native Method)
11-12 13:05:14.049: E/AndroidRuntime(10535): Caused by: java.lang.NullPointerException
11-12 13:05:14.049: E/AndroidRuntime(10535): at com.example.rectangle.MainActivity.onCreate(MainActivity.java:46)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.Activity.performCreate(Activity.java:5248)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
11-12 13:05:14.049: E/AndroidRuntime(10535): ... 11 more
Fragment_main
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/heightTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/widthTextView"
android:layout_below="#+id/widthTextView"
android:layout_marginTop="29dp"
android:text="Height"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/areaTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/heightTextView"
android:layout_below="#+id/heightTextView"
android:layout_marginTop="30dp"
android:text="Area"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/perimeterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/areaTextView"
android:layout_below="#+id/areaTextView"
android:layout_marginTop="40dp"
android:text="Perimeter"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/heightEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/heightTextView"
android:layout_alignLeft="#+id/widthEditText"
android:layout_alignRight="#+id/widthEditText"
android:ems="10"
android:inputType="numberSigned"
android:text="0.0" />
<TextView
android:id="#+id/widthTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="35dp"
android:text="Width"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/widthEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/heightTextView"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="numberDecimal"
android:text="0.0" />
<TextView
android:id="#+id/areaOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/areaTextView"
android:layout_marginLeft="38dp"
android:layout_toRightOf="#+id/perimeterTextView"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/perimterOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/perimeterTextView"
android:layout_alignBottom="#+id/perimeterTextView"
android:layout_alignLeft="#+id/areaOutput"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Try this:
TextView.OnEditorActionListener listener = new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
calculateAreaAndPerimeter();
return false;
}
};
The compile may still want to the one you have, and if, so create one like the above.
I think you have to tell the compiler its a listener, even though it may have created the method you have. Android Studio doesn't create listener syntax very well and I typically have to go back and surround a new public method with the listener stuff. Hope that works!
When I start the activity on my phone, it says that the app is not responding. The problem is the back button which I can't seem to program to make it gather the previous text from the textView.
Xml code for activity
<RelativeLayout 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:background="#drawable/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Author" >
<TextView
android:id="#+id/textView1"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/button_shape"
android:text="#string/Getstarted"
android:textColor="#FFFFFF"
android:textSize="23sp" />
<ImageButton
android:id="#+id/next"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="14dp"
android:background="#drawable/button_shape"
android:contentDescription="#string/Next"
android:onClick="NextQuote"
android:src="#drawable/navigationnextitem" />
<ImageButton
android:id="#+id/share"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/next"
android:layout_centerHorizontal="true"
android:background="#drawable/button_shape"
android:contentDescription="#string/share"
android:onClick="Sharing"
android:src="#drawable/socialshare" />
<ImageButton
android:id="#+id/back"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/next"
android:background="#drawable/button_shape"
android:contentDescription="#string/Back"
android:onClick="PreviousQuote"
android:src="#drawable/navigationpreviousitem" />
</RelativeLayout>
Java code for activity
package com.android.motivateme3;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
public class Author extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_author);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
Button NextQuote = (Button)findViewById(R.id.next);
final TextView display = (TextView) findViewById(R.id.textView1);
NextQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
int rNumber = numGen.nextInt(10);
if (rNumber == 0)
{
display.setText(R.string.Author1);
}
else if (rNumber == 1)
{
display.setText(R.string.Author2);
}
else if (rNumber == 2)
{
display.setText(R.string.Author3);
}
else if (rNumber == 3)
{
display.setText(R.string.Author4);
}
else if (rNumber == 4)
{
display.setText(R.string.Author5);
}
else if (rNumber == 5)
{
display.setText(R.string.Author6);
}
else if (rNumber == 6)
{
display.setText(R.string.Author7);
}
else if (rNumber == 7)
{
display.setText(R.string.Author8);
}
else if (rNumber == 8)
{
display.setText(R.string.Author9);
}
else if (rNumber == 9)
{
display.setText(R.string.Author10);
} }
});
}
ImageButton Sharing = (ImageButton)findViewById(R.id.share);
Sharing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
TextView text = (TextView)findViewById(R.id.textView1);
String quote = text.getText().toString();{
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("plain/text");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "This is a great quote (from the Motivate Me! app)");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, quote);
startActivity(Intent.createChooser(shareIntent, "Share via:"));}}});
Button BackQuote = (Button)findViewById(R.id.back);
final TextView display = (TextView) findViewById(R.id.textView1);
BackQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String prev = (String) display.getText();
display.setText(prev);
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.author, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the stack trace
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.ActivityThread.main(ActivityThread.java:4441)
04-03 14:29:34.174: E/AndroidRuntime(17383): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 14:29:34.174: E/AndroidRuntime(17383): at java.lang.reflect.Method.invoke(Method.java:511)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
04-03 14:29:34.174: E/AndroidRuntime(17383): at dalvik.system.NativeStart.main(Native Method)
04-03 14:29:34.174: E/AndroidRuntime(17383): Caused by: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.motivateme3.Author.setupActionBar(Author.java:36)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.motivateme3.Author.onCreate(Author.java:25)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.Activity.performCreate(Activity.java:4465)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
04-03 14:29:34.174: E/AndroidRuntime(17383): ... 11 more
04-03 14:29:41.664: I/Process(17383): Sending signal. PID: 17383 SIG: 9
It seems to me that R.id.next refers to an ImageButton, which cannot be cast into a Button, since it is not a subclass of a Button
Do you happen to see a ClassCastException?
To fix that particular issue, replace:
Button NextQuote = (Button)findViewById(R.id.next);
with
ImageButton NextQuote = (ImageButton)findViewById(R.id.next);