Null Pointer Exception need help figuring it out [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm attempting to create an application that keeps track of statistics throughout your golf game and generates a tip catered to your golf game if need be. I am keeping track of the holes by putting them into an array list. I found that you can pass objects between activities using googles GSON, I followed the tutorial but I feel that this passing of the array between activities is what ultimately is causing the NPE, but I am not sure.
Here is the full stack trace
11-04 11:06:02.218: E/Trace(774): error opening trace file: No such file or directory (2)
11-04 11:06:02.949: D/dalvikvm(774): GC_FOR_ALLOC freed 77K, 2% free 10958K/11143K, paused 46ms, total 48ms
11-04 11:06:03.048: D/dalvikvm(774): GC_CONCURRENT freed 168K, 3% free 11241K/11527K, paused >25ms+5ms, total 65ms
11-04 11:06:03.058: D/dalvikvm(774): WAIT_FOR_CONCURRENT_GC blocked 29ms
11-04 11:06:03.448: D/gralloc_goldfish(774): Emulator without GPU emulation detected.
11-04 11:06:06.168: D/AndroidRuntime(774): Shutting down VM
11-04 11:06:06.168: W/dalvikvm(774): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-04 11:06:06.208: E/AndroidRuntime(774): FATAL EXCEPTION: main
11-04 11:06:06.208: E/AndroidRuntime(774): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.testapp/com.example.testapp.StatActivity}: java.lang.NullPointerException
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.os.Looper.loop(Looper.java:137)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-04 11:06:06.208: E/AndroidRuntime(774): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 11:06:06.208: E/AndroidRuntime(774): at java.lang.reflect.Method.invoke(Method.java:511)
11-04 11:06:06.208: E/AndroidRuntime(774): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-04 11:06:06.208: E/AndroidRuntime(774): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 11:06:06.208: E/AndroidRuntime(774): at dalvik.system.NativeStart.main(Native Method)
11-04 11:06:06.208: E/AndroidRuntime(774): Caused by: java.lang.NullPointerException
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.Activity.findViewById(Activity.java:1825)
11-04 11:06:06.208: E/AndroidRuntime(774): at com.example.testapp.StatActivity.<init>(StatActivity.java:38)
11-04 11:06:06.208: E/AndroidRuntime(774): at java.lang.Class.newInstanceImpl(Native Method)
11-04 11:06:06.208: E/AndroidRuntime(774): at java.lang.Class.newInstance(Class.java:1319)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-04 11:06:06.208: E/AndroidRuntime(774): ... 11 more
11-04 11:06:06.388: D/dalvikvm(774): GC_CONCURRENT freed 266K, 4% free 11366K/11719K, paused >17ms+64ms, total 142ms
11-04 11:11:06.349: I/Process(774): Sending signal. PID: 774 SIG: 9
and the relevant activities
StatActivity
package com.example.testapp;
import java.util.ArrayList;
import java.util.List;
import com.example.testapp.StatActivity;
import com.example.testapp.CustomOnItemSelectedListener;
import com.example.testapp.R;
import com.google.gson.Gson;
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.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class StatActivity extends Activity implements OnClickListener {
private Spinner driving_spinner;
private Spinner approach_spinner;
private Spinner chipping_spinner;
private Spinner sandshot_spinner;
private Spinner putting_spinner;
private int hole = 1;
private boolean driving_spinner_selected = false;
private boolean approach_spinner_selected = false;
private boolean chipping_spinner_selected = false;
private boolean sandshot_spinner_selected = false;
private boolean putting_spinner_selected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stat);
Button homeButton = (Button) findViewById(R.id.homeButton);
Button helpButton = (Button) findViewById(R.id.helpButton);
Button nextHoleButton = (Button) findViewById(R.id.nextHoleButton);
driving_spinner = (Spinner) findViewById(R.id.drivingSpinner);
approach_spinner = (Spinner) findViewById(R.id.approachSpinner);
chipping_spinner = (Spinner) findViewById(R.id.chippingSpinner);
sandshot_spinner = (Spinner) findViewById(R.id.sandShotSpinner);
putting_spinner = (Spinner) findViewById(R.id.puttingSpinner);
nextHoleButton.setOnClickListener(this);
helpButton.setOnClickListener(this);
homeButton.setOnClickListener(this);
addItemsToDrivingSpinner();
addItemsToChippingSpinner();
addItemsToPuttingSpinner();
addItemsToApproachSpinner();
addItemsToSandShotSpinner();
addListenerOnDrivingSpinnerItemSelection();
addListenerOnChippingSpinnerItemSelection();
addListenerOnPuttingSpinnerItemSelection();
addListenerOnApproachSpinnerItemSelection();
addListenerOnSandShotSpinnerItemSelection();
}
Gson gS = new Gson();
String src = getIntent().getStringExtra("round");
Round round = gS.fromJson(src, Round.class);
// add items into spinner dynamically
public void addItemsToDrivingSpinner() {
List<String> list = new ArrayList<String>();
list.add("Left");
list.add("Right");
list.add("Fairway Hit");
list.add("Par Three");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
driving_spinner.setAdapter(dataAdapter);
}
public void addItemsToApproachSpinner() {
List<String> list = new ArrayList<String>();
list.add("Left");
list.add("Right");
list.add("Short");
list.add("Long");
list.add("Green Hit");
list.add("No Oppurtunity");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
approach_spinner.setAdapter(dataAdapter);
}
public void addItemsToChippingSpinner() {
List<String> list = new ArrayList<String>();
list.add("Yes Up and Down");
list.add("No Up and Down");
list.add("No Oppurtunity");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
chipping_spinner.setAdapter(dataAdapter);
}
public void addItemsToSandShotSpinner() {
List<String> list = new ArrayList<String>();
list.add("Yes Sand Save");
list.add("No Sand Save");
list.add("No Oppurtunity");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sandshot_spinner.setAdapter(dataAdapter);
}
public void addItemsToPuttingSpinner() {
List<String> list = new ArrayList<String>();
list.add("0");
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5+");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
putting_spinner.setAdapter(dataAdapter);
}
public void addListenerOnDrivingSpinnerItemSelection() {
driving_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
driving_spinner_selected = true;
}
public void addListenerOnApproachSpinnerItemSelection() {
approach_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
approach_spinner_selected = true;
}
public void addListenerOnChippingSpinnerItemSelection() {
chipping_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
chipping_spinner_selected = true;
}
public void addListenerOnPuttingSpinnerItemSelection() {
putting_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
putting_spinner_selected = true;
}
public void addListenerOnSandShotSpinnerItemSelection() {
sandshot_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
sandshot_spinner_selected = 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.stat, 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);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.homeButton){
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}else if(v.getId() == R.id.helpButton){
Intent intent = new Intent(getApplicationContext(), InstructionsActivity.class);
startActivity(intent);
}else if(v.getId() == R.id.nextHoleButton){
boolean filledIn = false;
if(driving_spinner_selected && chipping_spinner_selected && putting_spinner_selected && sandshot_spinner_selected && approach_spinner_selected)
filledIn = true;
if(filledIn) {
hole++;
round.setStats(String.valueOf(driving_spinner.getSelectedItem()),String.valueOf(putting_spinner.getSelectedItem()),String.valueOf(sandshot_spinner.getSelectedItem()),String.valueOf(chipping_spinner.getSelectedItem()),String.valueOf(approach_spinner.getSelectedItem()),hole);
Intent intent = new Intent(getApplicationContext(), StatActivity.class);
String target = gS.toJson(round);
intent.putExtra("round", target);
if(round.needTip()) {
String tip = round.generateTip();
Toast.makeText(StatActivity.this,
tip,
Toast.LENGTH_LONG).show();
}
startActivity(intent);
}
else {
Toast.makeText(StatActivity.this,
"Please fill in all statistics before continuing.",
Toast.LENGTH_SHORT).show();
}
}
}
}
HomeActivity
package com.example.testapp;
import com.google.gson.Gson;
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.view.View.OnClickListener;
import android.widget.Button;
public class HomeActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Button startRoundButton = (Button) findViewById(R.id.startRoundButton);
Button homeHelpButton = (Button) findViewById(R.id.homeHelpButton);
homeHelpButton.setOnClickListener(this);
startRoundButton.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
public void onClick(View v)
{
if(v.getId() == R.id.startRoundButton){
Round round = new Round();
Intent i = new Intent(getApplicationContext(),StatActivity.class);
Gson gS = new Gson();
String target = gS.toJson(round);
i.putExtra("round", target);
startActivity(i);
}else if(v.getId() == R.id.homeHelpButton){
Intent intent = new Intent(getApplicationContext(), InstructionsActivity.class);
startActivity(intent);
}
}
#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);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HomeActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".StatActivity"
android:label="#string/title_activity_stat" >
</activity>
<activity
android:name=".InstructionsActivity"
android:label="#string/title_activity_instructions" >
</activity>
</application>
</manifest>
Activity_Stat.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:background="#drawable/here_link"
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="com.example.testapp.StatActivity" >
<Spinner
android:id="#+id/puttingSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/approachSpinner"
android:layout_alignLeft="#+id/approachSpinner"
android:entries="#array/puttArr"
android:prompt="#string/putting" />
<Button
android:id="#+id/nextHoleButton"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/next_button_background" />
<Spinner
android:id="#+id/approachSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/sandShotSpinner"
android:layout_alignLeft="#+id/sandShotSpinner"
android:entries="#array/approachArr"
android:prompt="#string/aproach" />
<Spinner
android:id="#+id/sandShotSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/nextHoleButton"
android:layout_alignLeft="#+id/drivingSpinner"
android:layout_marginBottom="19dp"
android:entries="#array/sandShotArr"
android:prompt="#string/sand_shot" />
<Spinner
android:id="#+id/drivingSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/puttingSpinner"
android:layout_centerHorizontal="true"
android:entries="#array/drivingArr"
android:prompt="#string/driving" />
<Button
android:id="#+id/helpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/sandShotSpinner"
android:layout_alignTop="#+id/homeButton"
android:text="#string/help" />
<Button
android:id="#+id/homeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/nextHoleButton"
android:layout_alignParentLeft="true"
android:text="#string/home" />
<Spinner
android:id="#+id/chippingSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/drivingSpinner"
android:entries="#array/chippingArr"
android:prompt="#array/chippingArr" />
</RelativeLayout>
the Home activity is launched upon opening the app (which works) then the stat activity is started when Start round button is clicked and this is when the app stops.
any thoughts or ideas will be helpful. Thank you!

This line
String src = getIntent().getStringExtra("round");
is your problem. When it's invoked, there's no intent to get.
All setup that needs the intent needs to be done inside onCreate(), by which time the intent is available. Your code is being run at construction time, which is too early.
You haven't really provided enough info to determine whether this is what's generating the NPE that you're hitting, but it's certainly going to need fixing even if there's something else wrong too.

Related

TabHost addTabs on Android crashes the apk

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) {}
}

"unfortunately, app has stopped" on clicking login button [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 8 years ago.
I am new to this android. Whenever I click the login button, it says "unfortunately, your app has stopped".
There is no compile time error..
I am uploading my MainActivity.java, LoginActivity.java and manifest.xml files..
Please tell me whats the problem or am i doing something wrong?
//MainActivity.java
package com.satty002.swag;
import java.util.Locale;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.parse.ParseAnalytics;
import com.parse.ParseUser;
public class MainActivity extends Activity implements ActionBar.TabListener {
public static final String TAG = MainActivity.class.getSimpleName();
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpened(getIntent());
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
} else {
Log.i(TAG, currentUser.getUsername());
}
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
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_logout) {
ParseUser.logOut();
navigateToLogin();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return 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;
}
}
}
//LoginActivity.java
package com.satty002.swag;
import android.app.Activity;
import android.app.AlertDialog;
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.EditText;
import android.widget.TextView;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
public class LoginActivity extends Activity {
protected EditText mUsername;
protected EditText mPassword;
protected Button mLoginButton;
protected TextView mSignUpTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSignUpTextView = (TextView) findViewById(R.id.SignupText);
mSignUpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
}
});
mUsername = (EditText) findViewById(R.id.usernameField);
mPassword = (EditText) findViewById(R.id.passwordFiled);
mLoginButton = (Button) findViewById(R.id.loginButton);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
username.trim();
password.trim();
if(username.isEmpty() || password.isEmpty() )
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(R.string.login_error_message)
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else
{
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if(e == null)
{
//success
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(R.string.login_error_message)
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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);
}
}
//manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.satty002.swag"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" android:name="SwagApplication">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name=".SignupActivity"
android:label="#string/app_name"
android:parentActivityName=".LoginActivity">
</activity>
</application>
//Activity_login.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="com.satty002.swag.LoginActivity" >
<TextView
android:id="#+id/SignupText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/signup_text" />
<EditText
android:id="#+id/usernameField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="#string/username_hint" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/PasswordField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/usernameField"
android:layout_below="#+id/usernameField"
android:ems="10"
android:hint="#string/password_hint"
android:inputType="textPassword" />
<Button
android:id="#+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/PasswordField"
android:layout_below="#+id/PasswordField"
android:text="#string/login_button_label" />
//logcat
07-25 17:52:52.332: E/Trace(1627): error opening trace file: No such file or directory (2)
07-25 17:52:54.393: D/dalvikvm(1627): GC_CONCURRENT freed 274K, 7% free 6132K/6535K, paused 14ms+110ms, total 330ms
07-25 17:52:55.083: D/libEGL(1627): loaded /system/lib/egl/libEGL_emulation.so
07-25 17:52:55.093: D/(1627): HostConnection::get() New Host Connection established 0xb8462cf0, tid 1627
07-25 17:52:55.123: D/libEGL(1627): loaded /system/lib/egl/libGLESv1_CM_emulation.so
07-25 17:52:55.153: D/libEGL(1627): loaded /system/lib/egl/libGLESv2_emulation.so
07-25 17:52:55.363: W/EGL_emulation(1627): eglSurfaceAttrib not implemented
07-25 17:52:55.423: D/OpenGLRenderer(1627): Enabling debug mode 0
07-25 17:52:56.833: W/EGL_emulation(1627): eglSurfaceAttrib not implemented
07-25 17:52:56.833: I/Choreographer(1627): Skipped 37 frames! The application may be doing too much work on its main thread.
07-25 17:52:57.283: D/dalvikvm(1627): GC_CONCURRENT freed 189K, 5% free 6342K/6663K, paused 18ms+101ms, total 151ms
07-25 17:53:19.003: D/AndroidRuntime(1627): Shutting down VM
07-25 17:53:19.003: W/dalvikvm(1627): threadid=1: thread exiting with uncaught exception (group=0xb5f03288)
07-25 17:53:19.014: E/AndroidRuntime(1627): FATAL EXCEPTION: main
07-25 17:53:19.014: E/AndroidRuntime(1627): java.lang.NullPointerException
07-25 17:53:19.014: E/AndroidRuntime(1627): at com.satty002.swag.LoginActivity$2.onClick(LoginActivity.java:50)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.view.View.performClick(View.java:4084)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.view.View$PerformClick.run(View.java:16966)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.os.Handler.handleCallback(Handler.java:615)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.os.Handler.dispatchMessage(Handler.java:92)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.os.Looper.loop(Looper.java:137)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.app.ActivityThread.main(ActivityThread.java:4745)
07-25 17:53:19.014: E/AndroidRuntime(1627): at java.lang.reflect.Method.invokeNative(Native Method)
07-25 17:53:19.014: E/AndroidRuntime(1627): at java.lang.reflect.Method.invoke(Method.java:511)
07-25 17:53:19.014: E/AndroidRuntime(1627): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-25 17:53:19.014: E/AndroidRuntime(1627): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-25 17:53:19.014: E/AndroidRuntime(1627): at dalvik.system.NativeStart.main(Native Method)
I am going to guess that there is a null pointer somewhere in your onClick for your login activity. you should be able to figure this out by looking at your logcat which should tell you the exact line of code that is causing this crash. probably referencing an object that is not initialized / null
Edit
As stated you have a null reference on line 50 of LoginActivity:
java.lang.NullPointerException
07-25 17:53:19.014: E/AndroidRuntime(1627): at com.satty002.swag.LoginActivity$2.onClick(LoginActivity.java:50
you misspelled the password field reference:
mPassword = (EditText) findViewById(R.id.passwordFiled);
should be
mPassword = (EditText) findViewById(R.id.passwordField);
Line 50 in your LoginActivity throws NullPointerException,
line 50 will be somewhere around:
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
which means mUsername or mPassword is null
Check are you binding right layout to activity, and are you using correct ids

app closes when directed to second acivity

Hi I am new to Android stuff.Right now I'm following the tutorial given in developer.android.com/training/basics/firstapp/starting-activity.html and building my fist app.It was fine until I dealt with single activity.Later I have added second activity.When I click the button in first it should be directed to second activity.But on clicking first activity my app stops suddenly.Please help me.
here's the logcat
06-23 23:10:50.134: E/FragmentManager(437): No view found for id
0x7f05003c (com.example.honey:id/container) for fragment
PlaceholderFragment{43e98050 #0 id=0x7f05003c} 06-23 23:10:50.134:
E/FragmentManager(437): Activity state: 06-23 23:10:50.264:
E/AndroidRuntime(437): FATAL EXCEPTION: main 06-23 23:10:50.264:
E/AndroidRuntime(437): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{com.example.honey/com.example.honey.DisplayMessageActivity}:
java.lang.IllegalArgumentException: No view found for id 0x7f05003c
(com.example.honey:id/container) for fragment
PlaceholderFragment{43e98050 #0 id=0x7f05003c} 06-23 23:10:50.264:
E/AndroidRuntime(437): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
06-23 23:10:50.264: E/AndroidRuntime(437): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-23 23:10:50.264: E/AndroidRuntime(437): at
android.app.ActivityThread.access$2300(ActivityThread.java:125) 06-23
23:10:50.264: E/AndroidRuntime(437): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-23 23:10:50.264: E/AndroidRuntime(437): at
android.os.Handler.dispatchMessage(Handler.java:99) 06-23
23:10:50.264: E/AndroidRuntime(437): at
android.os.Looper.loop(Looper.java:123) 06-23 23:10:50.264:
E/AndroidRuntime(437): at
android.app.ActivityThread.main(ActivityThread.java:4627) 06-23
23:10:50.264: E/AndroidRuntime(437): at
java.lang.reflect.Method.invokeNative(Native Method) 06-23
23:10:50.264: E/AndroidRuntime(437): at
java.lang.reflect.Method.invoke(Method.java:521) 06-23 23:10:50.264:
E/AndroidRuntime(437): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-23 23:10:50.264: E/AndroidRuntime(437): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 06-23
23:10:50.264: E/AndroidRuntime(437): at
dalvik.system.NativeStart.main(Native Method) 06-23 23:10:50.264:
E/AndroidRuntime(437): Caused by: java.lang.IllegalArgumentException:
No view found for id 0x7f05003c (com.example.honey:id/container) for
fragment PlaceholderFragment{43e98050 #0 id=0x7f05003c} 06-23
23:10:50.264: E/AndroidRuntime(437): at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:930)
06-23 23:10:50.264: E/AndroidRuntime(437): at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
06-23 23:10:50.264: E/AndroidRuntime(437): at
android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-23 23:10:50.264: E/AndroidRuntime(437): at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
06-23 23:10:50.264: E/AndroidRuntime(437): at
android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
06-23 23:10:50.264: E/AndroidRuntime(437): at
android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
06-23 23:10:50.264: E/AndroidRuntime(437): at
android.app.Activity.performStart(Activity.java:3781) 06-23
23:10:50.264: E/AndroidRuntime(437): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2636)
06-23 23:10:50.264: E/AndroidRuntime(437): ... 11 more
1st activity java file
package com.example.honey;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
static final String EXTRA_MESSAGE = "com.example.honey.MESSAGE";
public void sendMessage(View view){ Intent intent=new
Intent(this,DisplayMessageActivity.class); EditText
editText=(EditText)findViewById(R.id.edit_query); String message =
editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE,
message); startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new
PlaceholderFragment())
.commit();
}
}
#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;
}
}
}
}
1st activity fragment_main.xml
For 2nd activity
package com.example.honey;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View; import
android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); Intent intent=getIntent();
setContentView(R.layout.activity_display_message);
String message=intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView =new TextView(this);
textView.setText(message);
setContentView(textView);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, 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_display_message,container, false);
return rootView;
}
}
}
XML file
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="com.example.honey.DisplayMessageActivity$PlaceholderFragment"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></TextView> </LinearLayout>
manifest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.honey.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.honey.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.first.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.first.MainActivity" />
</activity>
</application>
You're making a silly error in the second activity code due to copy pasting:
DisplayMessageActivity:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
You're trying to add the PlaceholderFragment to the R.id.container, when the content view of the second activity is the TextView, which does NOT have the container, aka the layout specified by R.id.container does not exist in the second activity.
Remove these lines from the second activity and it should work.
You forgot to add the activity to the manifest I think...
<activity
android:name="DisplayMessageActivity"
android:label="#string/..." >
</activity>
Check your XML layout for MainActivity, you specify findViewById(R.id.edit_query) for your EditText which was never declared.
Add the stared line to your fragment_main.xml file
`<EditText
**android:id="#+id/edit_query**
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message"
android:layout_weight="1"/>`

I can't move from current activity to another activity

when try to click on New Activity Button in my MainActivity , my app crash and closed . whit this error on screen " unfortunately[ App Name ] has stopped "
I google this problem and i can't find any Definitive solution.
here is logCat Log , First Java Source ( MainActivity.java ) and seccond java source ( Seccond.java ) .
Logcat Log :
05-03 00:05:17.750: E/AndroidRuntime(1091): FATAL EXCEPTION: main
05-03 00:05:17.750: E/AndroidRuntime(1091): Process: com.example.helloworld, PID: 1091
05-03 00:05:17.750: E/AndroidRuntime(1091): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld/com.example.helloworld.Seccond}: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.helloworld:id/container) for fragment PlaceholderFragment{b2d2faf8 #0 id=0x7f05003c}
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.os.Handler.dispatchMessage(Handler.java:102)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.os.Looper.loop(Looper.java:136)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-03 00:05:17.750: E/AndroidRuntime(1091): at java.lang.reflect.Method.invokeNative(Native Method)
05-03 00:05:17.750: E/AndroidRuntime(1091): at java.lang.reflect.Method.invoke(Method.java:515)
05-03 00:05:17.750: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-03 00:05:17.750: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-03 00:05:17.750: E/AndroidRuntime(1091): at dalvik.system.NativeStart.main(Native Method)
05-03 00:05:17.750: E/AndroidRuntime(1091): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.helloworld:id/container) for fragment PlaceholderFragment{b2d2faf8 #0 id=0x7f05003c}
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.Activity.performStart(Activity.java:5241)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
MainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
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.ImageView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Start
Button btn_img = (Button) findViewById(R.id.btn_image);
Button btn = (Button) findViewById(R.id.btn_Click);
final TextView txt = (TextView) findViewById(R.id.txt_view);
Button btn_avtivity = ( Button) findViewById(R.id.btn_activity);
// For button click
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
txt.setText(" Amin Bassam ");
}
});
// Image show
btn_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
ImageView img=(ImageView)findViewById(R.id.img_view);
img.setImageResource(R.drawable.amin);
}
});
btn_avtivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(),Seccond.class);
startActivity(intent);
}
});
// Open Activities
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new Fragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
}
Seccond.java
package com.example.helloworld;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class Seccond extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seccond);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.seccond, 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.activity_seccond,
container, false);
return rootView;
}
}
}
Activity_main.Xml
<RelativeLayout 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="com.example.helloworld.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/txt_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btn_Click"
android:layout_alignParentTop="true"
android:layout_marginTop="98dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/btn_Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="66dp"
android:text="Click"
tools:ignore="HardcodedText" />
"res/layout/activity_main.xml"
<Button
android:id="#+id/btn_image"
style="#style/AppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btn_Click"
android:layout_alignBottom="#+id/btn_Click"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/btn_Click"
android:text="Image"
tools:ignore="HardcodedText" />
<ImageView
android:id="#+id/img_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btn_image"
android:layout_centerVertical="true"
android:scaleType="center"
android:src="#drawable/abc_ab_solid_light_holo"
tools:ignore="ContentDescription" />
<Button
android:id="#+id/btn_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/btn_image"
android:text="New Activities"
tools:ignore="HardcodedText" />
</RelativeLayout>
Seccond_activity.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:background="#A8B007"
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="com.example.helloworld.Seccond$PlaceholderFragment" >
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.helloworld.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.helloworld.Seccond"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
No view found for id 0x7f05003c (com.example.helloworld:id/container) for fragment PlaceholderFragment
The error is saying it cannot find the view with an id of container for the fragment placeholder to go into.
setContentView(R.layout.activity_seccond);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
This part of the code is the main problem. In the add() for the getSupportFragmentManager, it is saying to create the fragment and put it in a view with the id container. But the layout specified in setContentView does not have a view with an id of container. So there needs to be a layout file with a View (like a frame) with an id of container, so that when the fragment layout loads, it can go into that view.
Try adding a file to layouts called activity_frame_seccond.xml with:
<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" />
Which is a frame with the id 'container'.
Change this line in Seccond.java:
setContentView(R.layout.activity_seccond);
for
setContentView(R.layout.activity_frame_seccond);
and see if that works.
With this code you are using the new file activity_frame_seccond.xml as the layout for the activity, and the first file activity_seccond.xml as the fragment that will put in the frame element (because it has the id container).
If this doesn't work let me know and I will have another look.
Check this line in your Fragment class :
View rootView = inflater.inflate(R.layout.activity_seccond,
container, false);
i think the Returned View is Null
Remove this line from your manifest
<activity
android:name="com.example.helloworld.Second"
android:label="#string/app_name" >
>
</activity>
and try
try in this way
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this,Seccond.class);
startActivity(intent);
}

android getViewById() NullPointerException

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

Categories