android getViewById() NullPointerException - java

I'm trying to make my app changes its layout when user rotate the screen.
When i launch the app while the screen of virtual machines is in portrait position.
The app is ok when launch but when I rotate the screen to landscape, the app will stops and the logCat shows a nullPointerException at line 40
line 39 btn=(Button)findViewById(R.id.btn);
line 40 btn.setOnClickListener(btnListener);
I think the findViewById() method is returning null, but i dont know why.
Also, if i launch the app while screen in landscape position, the same error occured.
SOLVED: the problem might be the arrangement of nested if, add braces for every if and else-if do solve this problem
Here are the codes:
MainActivity.java
package com.example.test;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
SharedPreferences preference;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preference = getSharedPreferences("preferences", MODE_PRIVATE);
if(getResources().getConfiguration().orientation == 1)
if(preference.getInt("THE_CHECKED", 0) == 0)
setContentView(R.layout.portrait_black);
else if(preference.getInt("THE_CHECKED", 0) == 1)
setContentView(R.layout.portrait_white);
else if(getResources().getConfiguration().orientation == 2)
if(preference.getInt("THE_CHECKED", 0) == 0)
setContentView(R.layout.landscape_black);
else if(preference.getInt("THE_CHECKED", 0) == 1)
setContentView(R.layout.landscape_white);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(btnListener);
}
private Button.OnClickListener btnListener = new Button.OnClickListener()
{
public void onClick(View v)
{
Toast toast1 = Toast.makeText(MainActivity.this, "HI", Toast.LENGTH_LONG);
toast1.show();
}
};
private DialogInterface.OnClickListener theDialogListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
SharedPreferences.Editor editor = preference.edit();
switch(which)
{
case 0: //Black
editor.putInt("THE_CHECKED", 0);
break;
case 1: //White
editor.putInt("THE_CHECKED", 1);
break;
}
editor.commit();
((Dialog)dialog).dismiss();
onCreate(new Bundle());
}
};
#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)
{
SharedPreferences.Editor editor = preference.edit();
switch (item.getItemId())
{
case R.id.theme:
Builder theDialog = new AlertDialog.Builder(this);
theDialog.setTitle("Theme");
theDialog.setSingleChoiceItems(R.array.theme_menu, preference.getInt("THE_CHECKED", 0), theDialogListener);
theDialog.show();
break;
}
editor.commit();
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
onCreate(new Bundle());
}
}
Layouts
portrait_white.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="portrait"
android:textSize="30sp"
android:textColor="#000000" />
</LinearLayout>
portrait_black.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="portrait"
android:textSize="30sp"
android:textColor="#000000" />
</LinearLayout>
landscape_white.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="landscape"
android:textSize="30sp"
android:textColor="#000000" />
</LinearLayout>
landscape_black.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="landscape"
android:textSize="30sp"
android:textColor="#000000" />
</LinearLayout>
LogCat(when i launch the app while screen is in landscape position)
02-21 01:26:53.895: D/AndroidRuntime(1836): Shutting down VM
02-21 01:26:53.925: W/dalvikvm(1836): threadid=1: thread exiting with uncaught exception (group=0x41465700)
02-21 01:26:53.935: E/AndroidRuntime(1836): FATAL EXCEPTION: main
02-21 01:26:53.935: E/AndroidRuntime(1836): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.os.Looper.loop(Looper.java:137)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.main(ActivityThread.java:5103)
02-21 01:26:53.935: E/AndroidRuntime(1836): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 01:26:53.935: E/AndroidRuntime(1836): at java.lang.reflect.Method.invoke(Method.java:525)
02-21 01:26:53.935: E/AndroidRuntime(1836): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-21 01:26:53.935: E/AndroidRuntime(1836): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-21 01:26:53.935: E/AndroidRuntime(1836): at dalvik.system.NativeStart.main(Native Method)
02-21 01:26:53.935: E/AndroidRuntime(1836): Caused by: java.lang.NullPointerException
02-21 01:26:53.935: E/AndroidRuntime(1836): at com.example.test.MainActivity.onCreate(MainActivity.java:40)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.Activity.performCreate(Activity.java:5133)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-21 01:26:53.935: E/AndroidRuntime(1836): ... 11 more
Thanks.

You don't have setContentView() in your Activity, hence, there's actually no View referenced to your activity and no views to find using findViewById() method, make sure the setContentView() was actually called...
Regards!

Use it this way. You have written nested if else and the second condition will never be executed in landscape mode i.e. orientation==2
package com.example.test;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
SharedPreferences preference;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preference = getSharedPreferences("preferences", MODE_PRIVATE);
if(getResources().getConfiguration().orientation == 1)
{
if(preference.getInt("THE_CHECKED", 0) == 0)
setContentView(R.layout.portrait_black);
else if(preference.getInt("THE_CHECKED", 0) == 1)
setContentView(R.layout.portrait_white);
}
else if(getResources().getConfiguration().orientation == 2)
if(preference.getInt("THE_CHECKED", 0) == 0)
setContentView(R.layout.landscape_black);
else if(preference.getInt("THE_CHECKED", 0) == 1)
setContentView(R.layout.landscape_white);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(btnListener);
}
private Button.OnClickListener btnListener = new Button.OnClickListener()
{
public void onClick(View v)
{
Toast toast1 = Toast.makeText(MainActivity.this, "HI", Toast.LENGTH_LONG);
toast1.show();
}
};
private DialogInterface.OnClickListener theDialogListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
SharedPreferences.Editor editor = preference.edit();
switch(which)
{
case 0: //Black
editor.putInt("THE_CHECKED", 0);
break;
case 1: //White
editor.putInt("THE_CHECKED", 1);
break;
}
editor.commit();
((Dialog)dialog).dismiss();
onCreate(new Bundle());
}
};
#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)
{
SharedPreferences.Editor editor = preference.edit();
switch (item.getItemId())
{
case R.id.theme:
Builder theDialog = new AlertDialog.Builder(this);
theDialog.setTitle("Theme");
theDialog.setSingleChoiceItems(R.array.theme_menu, preference.getInt("THE_CHECKED", 0), theDialogListener);
theDialog.show();
break;
}
editor.commit();
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
onCreate(new Bundle());
}
}

Could you print the getResources().getConfiguration().orientation, I think it may be others values than 1 and 2
Infact, we have 4 value of getResources().getConfiguration().orientation: Configuration.ORIENTATION_PORTRAIT = 1, Configuration.ORIENTATION_LANDSCAPE =2, Configuration.ORIENTATION_SQUARE =3, Configuration.ORIENTATION_UNDEFINED =0

Related

java.lang.RuntimeException: Unable to start activity ComponentInfo (android eclipse)

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.

App Crashing (Unable to start ComponentInfo Error) [duplicate]

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!

Crash when adding a OnClickListener to a Button

I'm a total newbie with Android, and I'm trying to switch between two activities ("MainActivity" and "LoginDisplayActivity") and adding the "OnClickListener" seem to make my app crash on startup.
Here is my code :
package info.dremor.kronos;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new MainFragment()).commit();
}
final Button loginButton = (Button) findViewById(R.id.connect);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LoginDisplayActivity.class);
startActivity(intent);
}
});
}
#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 MainFragment extends Fragment {
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
trace :
05-26 15:48:11.286: D/AndroidRuntime(947): Shutting down VM
05-26 15:48:11.286: W/dalvikvm(947): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
05-26 15:48:11.296: E/AndroidRuntime(947): FATAL EXCEPTION: main
05-26 15:48:11.296: E/AndroidRuntime(947): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.dremor.kronos/info.dremor.kronos.MainActivity}: java.lang.NullPointerException
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.access$600(ActivityThread.java:130)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.os.Handler.dispatchMessage(Handler.java:99)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.os.Looper.loop(Looper.java:137)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.main(ActivityThread.java:4745)
05-26 15:48:11.296: E/AndroidRuntime(947): at java.lang.reflect.Method.invokeNative(Native Method)
05-26 15:48:11.296: E/AndroidRuntime(947): at java.lang.reflect.Method.invoke(Method.java:511)
05-26 15:48:11.296: E/AndroidRuntime(947): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
05-26 15:48:11.296: E/AndroidRuntime(947): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-26 15:48:11.296: E/AndroidRuntime(947): at dalvik.system.NativeStart.main(Native Method)
05-26 15:48:11.296: E/AndroidRuntime(947): Caused by: java.lang.NullPointerException
05-26 15:48:11.296: E/AndroidRuntime(947): at info.dremor.kronos.MainActivity.onCreate(MainActivity.java:31)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.Activity.performCreate(Activity.java:5008)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
05-26 15:48:11.296: E/AndroidRuntime(947): ... 11 more
activity_main.xml :
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.dremor.kronos.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_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: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="info.dremor.kronos.MainActivity$PlaceholderFragment" >
<Button
android:id="#+id/connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="35dp"
android:text="#string/connect" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:text="#string/login_greeting" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:text="#string/login" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:ems="10" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:text="#string/password" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/textView2"
android:layout_marginTop="35dp"
android:ems="10"
android:inputType="textPassword" />
</RelativeLayout>
Can someone help me?
In your activity, you set the layout file like this:
setContentView(R.layout.activity_main);
This means, when you write findViewById, it will look within the activity_main.xml file.
Your button on the other hand is within another layout file.
Just move the click event into your fragment, and access the context using getActivity like so:
final Button loginButton = (Button) rootView.findViewById(R.id.connect);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LoginDisplayActivity.class);
startActivity(intent);
}
});
your button is in the fragment layout, you're "finding" it from the activity layout. Setup button onclick in the fragment onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final Button loginButton = (Button) rootView.findViewById(R.id.connect);
loginButton.setOnClickListener(new OnClickListener(){...})
return rootView;
}
Remove the button and code from onCreate and shift the button and clicklistener code to onCreateView like this:
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final Button loginButton = (Button) rootView.findViewById(R.id.connect);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LoginDisplayActivity.class);
startActivity(intent);
}
});
return rootView;
As your button is in fragment_main, not activity_main. The button is not found.

"Unfortunately, app has stopped" when Downloading file (Android) [duplicate]

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

How do I make the back button I created in the activity change the text in the textView to the previous text created by the random generator?

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);

Categories