I have my Random Number generator and it crashes when I I type in 0 in the 'numberTo' string and gives me int: "0". With this I cannot make remove the editText and show the hint because of the TextWatcher. Please help me with that! And guys how do I add a button with a different color, can you please explain?
This is my code:
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="bedi.gursimran.materialtest.MainActivity">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<TextView
android:textSize="68dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/random_text"
android:text="Number"
android:layout_marginTop="12dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="false"
android:layout_marginLeft="50dp"
/>
<EditText
android:layout_width="140dp"
android:layout_height="wrap_content"
android:inputType="number"
android:padding="12dp"
android:ems="10"
android:id="#+id/text_from"
android:maxLength="6"
android:hint="From"
android:layout_below="#+id/app_bar"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="24dp"
android:backgroundTint="#color/primaryColorDark"
android:textSize="#dimen/edit_text_size"/>
<EditText
android:layout_width="140dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:padding="12dp"
android:id="#+id/text_to"
android:layout_below="#+id/text_from"
android:layout_alignParentStart="true"
android:maxLength="8"
android:hint="To"
android:backgroundTint="#color/primaryColorDark"
android:layout_marginTop="8dp"
android:layout_marginLeft="10dp"
android:textSize="#dimen/edit_text_size"/>
<Button
android:layout_width="140dp"
android:layout_height="70dp"
android:text="Generate"
android:id="#+id/generate_button"
android:onClick="generate"
android:layout_below="#+id/app_bar"
android:layout_marginLeft="190dp"
android:layout_marginTop="51dp"
android:textColor="#fffafafa"
android:textSize="22dp"
android:backgroundTint="#color/accentColor"
/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base">
<!-- Customize your theme here. -->
</style>
<!--Base theme-->
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar" >
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryDark">#color/primaryColorDark</item>
<item name="colorAccent">#color/accentColor</item>
<!-- Generate Button Color -->
<item name="android:colorButtonNormal">#color/primaryColor</item>
</style>
<!--Action Bar theme-->
<style name="MyCustomToolBarTheme" parent="ThemeOverlay.AppCompat.Light">
<!--The title-->
<item name="android:textColorPrimary">#FFFFFF</item>
<item name="android:textColor">#FFFFFF</item>
<!--The 'overflow icon-->
<item name="android:textColorSecondary">#FFFFFF</item>
</style>
<style name="ActionBarPopupThemeOverlay" parent="ThemeOverlay.AppCompat.Light" >
<item name="android:background">#android:color/white</item>
<item name="android:textColor">#de000000</item>
</style>
</resources>
app_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/primaryColor"
app:theme="#style/MyCustomToolBarTheme"
android:paddingTop="#dimen/app_bar_top_padding"
android:elevation="#dimen/action_bar_elevation"
app:popupTheme="#style/ActionBarPopupThemeOverlay"
>
</android.support.v7.widget.Toolbar>
And most importantly... MainActivity.java
public class MainActivity extends ActionBarActivity implements TextWatcher {
private Toolbar toolbar;
TextView randomText;
EditText editTextFrom;
EditText editTextTo;
Button generate_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//toolbar= (Toolbar) findViewById(R.id.app_bar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
//Generated Number
randomText = (TextView) findViewById(R.id.random_text);
Typeface myCustomFontTextView = Typeface.createFromAsset(getAssets(), "fonts/RobotoCondensed-Light.ttf");
randomText.setTypeface(myCustomFontTextView);
//From Text
editTextFrom = (EditText) findViewById(R.id.text_from);
Typeface myCustomFontEditViewFrom = Typeface.createFromAsset(getAssets(), "fonts/RobotoCondensed-Regular.ttf");
editTextFrom.setTypeface(myCustomFontEditViewFrom);
editTextFrom.addTextChangedListener(this);
//To Text
editTextTo = (EditText) findViewById(R.id.text_to);
Typeface myCustomFontEditViewTo = Typeface.createFromAsset(getAssets(), "fonts/RobotoCondensed-Regular.ttf");
editTextTo.setTypeface(myCustomFontEditViewTo);
editTextTo.addTextChangedListener(this);
//Generate Button
generate_button = (Button) findViewById(R.id.generate_button);
Typeface myCustomFontButton = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf");
generate_button.setTypeface(myCustomFontButton);
}
#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) {
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
// if (id == R.id.navigate) {
// startActivity(new Intent(this, SubActivity.class));
// }
return super.onOptionsItemSelected(item);
}
public void generate(View view) {
//text
EditText from = (EditText) findViewById(R.id.text_from);
EditText to = (EditText) findViewById(R.id.text_to);
String stringFrom, stringTo;
stringFrom = from.getText().toString();
stringTo = to.getText().toString();
int numberFrom, numberTo;
if (stringFrom.equals("")) {
stringFrom = "0";
}
if (stringTo.equals("")) {
stringTo = "0";
}
numberFrom = Integer.parseInt(stringFrom);
numberTo = Integer.parseInt(stringTo);
Random random = new Random();
int number = random.nextInt(numberTo + 1);
if(numberFrom != numberTo) {
while (number < numberFrom || number > numberTo) {
number = random.nextInt(numberTo + 1);
}
} else {
numberFrom = numberTo = number;
}
// } catch (NumberFormatException e) {}
try {
TextView myText = (TextView) findViewById(R.id.random_text);
String myString = String.valueOf(number);
myText.setText(myString);
} catch (NumberFormatException e) {
TextView myText = (TextView) findViewById(R.id.random_text);
myText.setText("Enter a number greater than zero");
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable editable) {
int numberto;
try {
numberto = Integer.parseInt(editable.toString());
} catch (NumberFormatException e) {
numberto = 0;
}
if (numberto == 0) {
editable.replace(0, editable.length(), "1");
}
}
}
edit
The errors went away as I took the implements TextWatcher out. Please help me with the button colors, I still don't know how to have 2 different colored buttons. Thanks!
edit 2 Gives me this log when I put both as null. Please help!!
2414-2414/bedi.gursimran.materialtest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: bedi.gursimran.materialtest, PID: 2414
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalArgumentException: n <= 0: 0
at java.util.Random.nextInt(Random.java:182)
at bedi.gursimran.materialtest.MainActivity.generate(MainActivity.java:120)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Related
This app is all about clicking a Button and there is a TextBox which changes its content when clicked.
MainActivity.java
package com.lost.eventhandling;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button willybutton=(Button)findViewById(R.id.willybutton);
assert willybutton != null;
willybutton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
TextView willytext=(TextView)findViewById(R.id.willytext);
willytext.setText("I DID IT ");
}
}
);
}
#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);
}
}
Now for xml code I had
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.lost.eventhandling.MainActivity"
android:background="#71f8bd">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/willy_text"
android:id="#+id/willytext"
android:textColor="#e83858"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="179dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/willy_button"
android:id="#+id/willybutton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#764045"/>
</RelativeLayout>
Whenever I debug my application it sends a message it unfortuantely stopped.
And my android monitor gives me this red coloured text:
FATAL EXCEPTION: main
Process: com.lost.eventhandling, PID: 2449
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lost.eventhandling/com.lost.eventhandling.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.lost.eventhandling.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Replace yours OnclickListener code of Button with these lines of code:
Button willybutton=(Button)findViewById(R.id.willybutton);
TextView willytext=(TextView)findViewById(R.id.willytext);
willybutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////PERFORM YOURS OPERATION HERE
}
});
Hello i'm struggling with these error for past of couple of hours to no avail. I am trying to pass data from my activity to the fragment but not succeeding in doing so. My guess it's complaining about my <fragment> in activity_second.xml file. My guess might be wrong. Has anyone encountered this error? But i don't know how to resolve this error.Would some please guide in me what i did wrong. Below is my code:
first_fragment.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragmentPic" >
<TextView
android:id="#+id/textName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/users_FirstName"
android:textSize="#dimen/font_size"
android:layout_gravity="center_horizontal"/>
<com.facebook.login.widget.ProfilePictureView
android:id="#+id/profilePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
>
</com.facebook.login.widget.ProfilePictureView>
</LinearLayout>
FirstFragment.java:
public class FirstFragment extends Fragment {
private ProfilePictureView profilePictureView;
private TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.first_fragment, container, false);
Bundle bundle = new Bundle();
bundle = this.getArguments();
String profileId = bundle.getString("profileId"); //complains here and returns null
TextView textView = (TextView)rootView.findViewById(R.id.textName);
textView.setText(bundle.getString("names"));
return rootView;
}
}
activity_second.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/backgroundColor"
>
<include android:id="#+id/toolBar"
layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/first_fragment"
class="edu.sjsu.cmpe277.termproject.Fragments.FirstFragment"
android:id="#+id/fragment1"
/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
secondActivity.java:
public class secondActivity extends AppCompatActivity {
private Intent intent;
private Toolbar toolbar;
private String firstName, profileId;
private FirstFragment firstFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
intent = getIntent();
firstName = intent.getStringExtra("firstName");
profileId = intent.getStringExtra("Id");
toolbar = (Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
toolbar.setLogo(R.drawable.ic_menu_image);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
firstFragment = new FirstFragment();
Bundle bundle = new Bundle();
bundle.putString("names", firstName);
bundle.putString("profileId", profileId);
firstFragment.setArguments(bundle);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.drawer, firstFragment,"newFrag").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.menu_second, 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.
switch(item.getItemId()) {
case android.R.id.home:
Intent homeIntent = new Intent(this, secondActivity.class );
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this error below:
29 01:50:11.402 13536-13536/edu.sjsu.cmpe277.termproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: edu.sjsu.cmpe277.termproject, PID: 13536
java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.sjsu.cmpe277.termproject/edu.sjsu.cmpe277.termproject.secondActivity}: android.view.InflateException: Binary XML file line #82: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: android.view.InflateException: Binary XML file line #82: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at edu.sjsu.cmpe277.termproject.secondActivity.onCreate(secondActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at edu.sjsu.cmpe277.termproject.Fragments.FirstFragment.onCreateView(FirstFragment.java:44)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1185)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1287)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2243)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:278)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:78)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at edu.sjsu.cmpe277.termproject.secondActivity.onCreate(secondActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
Get rid of
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/first_fragment"
class="edu.sjsu.cmpe277.termproject.Fragments.FirstFragment"
android:id="#+id/fragment1"
/>
and use only the explicitly transaction you are using in your Activity. You can't pass a Bundle, declaring a Fragment in the layout, and try to accessing it, is making your app crash
In your activity_second.xml file, change:
class="edu.sjsu.cmpe277.termproject.Fragments.FirstFragment"
to
android:name="edu.sjsu.cmpe277.termproject.Fragments.FirstFragment"
That's the correct prefix to use.
I'm rather new to android programming, and am running into my old friend the NullPointerException...
I've been on it for quite a while now, but can't figure out what is wrong.
basicly gives me a NullPointerException when I try to call any .setText() methods, maybe someone sees what I'm doing wrong here...(though i tried to follow examples as close as possible)
public class lessonView extends Activity {
TextView adressOfLecture;
TextView lecturer;
TextView lesson;
Lecture lecture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson_view);
Bundle data = getIntent().getExtras();
lecture = (Lecture) data.getParcelable("student");
adressOfLecture = (TextView)findViewById(R.id.lectureViewAdressLabel);
lecturer = (TextView)findViewById(R.id.lectureViewLecturerLabel);
lesson = (TextView)findViewById(R.id.lectureViewTitle);
updateLabels();
}
#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_lesson_view, 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);
}
private void updateLabels(){
adressOfLecture.setText(lecture.getRoom());
lecturer.setText(lecture.getTutor());
lesson.setText(lecture.getName());
}
}
also, here's my xml file:
<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.coronarip7.app.stupla.lessonView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(ort)"
android:id="#+id/lectureViewAdressLabel"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/lectureViewTitle"
android:layout_marginRight="86dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dozent"
android:id="#+id/lectureViewLecturerLabel"
android:layout_toEndOf="#+id/lectureViewTitle"
android:layout_alignTop="#+id/lectureViewAdressLabel"
android:layout_alignParentEnd="true"
android:layout_marginRight="27dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lectureViewTitle"
android:gravity="center_horizontal"
android:text="test"
android:textSize="40dp"
android:textStyle="bold"
android:padding="10dp"
android:layout_row="0"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
and the logcat I'm getting:
04-25 01:23:51.058 12236-12236/com.coronarip7.app.stupla E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.coronarip7.app.stupla, PID: 12236
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coronarip7.app.stupla/com.coronarip7.app.stupla.lessonView}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5081)
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:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.coronarip7.app.stupla.lessonView.updateLabels(lessonView.java:59)
at com.coronarip7.app.stupla.lessonView.onCreate(lessonView.java:31)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5081)
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:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
seriously, I am out of ideas on how to fix it...
First check if you properly put the extra in the intent. Then I would use the following test in your onCreate method:
Intent intent = getIntent();
if (intent.hasExtra("student")){
lecture = (Lecture) intent.getParcelableExtra("student");
}
Then test if lecture is null like Rami wrote earlier.
Ok guys, thanks for the suggestions, but I'll go the global route. I'll create a static version of my array (from which i wanted to pass an object via the Intent), and just pass an int[] array with the coordiantes and call it in the new view.
But thanks for the quick answers anyways!
(I'm new to stackoverflow, is there a way to mark a question as "solved", or "not-needed-to-be-solved-anymore"?)
Do not use static objects in your code like arrays, objects, they have globally available, you should create intent and add your data into your intent like and call your activity
Intent intent = new Intent ();
intent.putExtra ("student",value);
start activity with intent
And in your
lessonViewActivity check for intent like
Intent intent = getIntent();
if (intent.hasExtra("student")){
lecture = (Lecture) intent.getParcelableExtra("student");
if (lecture !=null){
updateLabels ();
}
}
I am building an app named Ping in Android Studio. So far my activities are LoginActivity ProfileActivity and Timeline. My issue is that a button in the layout corresponding to the Timeline activity has an onClick method that isn't working. When the button is clicked, the emulator gives the "Unfortunatley, Ping has stopped." I'm defining the buttons and onClick methods the same way I have for other buttons whose functions are working, just this one does not seem to work. I'm receiving an error saying the method can't be found, but I've written the method in the corresponding activity. Here is the logcat:
04-30 10:40:08.727 2075-2075/com.ping_social.www.ping E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.ping_social.www.ping, PID: 2075
java.lang.IllegalStateException: Could not find a method onProfilePress(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'profileButton'
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NoSuchMethodException: onProfilePress [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:4000)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Here is my Timeline activity class:
package com.ping_social.www.ping;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class TimeLine extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_line);
/*print log that shows we've got here*/
Log.i("LoginActivity", "Layout has been set");
}
#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_time_line, 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);
}
/*called when user presses the Log in button*/
public void onProfilePress(View view){
/*Log the button press*/
Log.i("TimeLine", "Has reached the onProfilePress method");
Intent intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
}
}
And here is my Timeline layout xml code:
<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"
android:theme="#style/GeneralTheme"
tools:context="com.ping_social.www.ping.TimeLine">
<TextView android:text="#string/no_pings" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textIsSelectable="false"
android:textColor="#color/PING_TOP_BAR_RED"
android:id="#+id/textView4" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/timeline_button"
android:id="#+id/timelineButton"
android:textColor="#color/PING_TOP_BAR_RED"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_ping_button"
android:id="#+id/newPingButton"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/activity_button"
android:id="#+id/activityButton"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/profile_button"
android:id="#+id/profileButton"
android:layout_weight="1"
android:onClick="onProfilePress"/>
</LinearLayout>
</RelativeLayout>
I'm pretty positive there are not spelling issues, and there are also no other buttons that share the same ID or methods that share the same name. Been stuck on this for a few days, any help is very much appreciated!
Ok, so I made my own test. I've put together a basic relative layout with a single button, put android:theme="#style/AppTheme" in it, and a button - app crashed with the same error. Then I removed android:theme attribute - onclick event fired as it should.
All the same happened when I used AppCompatActivity instead of now-deprecated ActionBarActivity.
It's hard for me to say why it doesn't work with android:theme. It's one of Lollipop's features, but I tried to launch in on API 5.0 emulator. The article states that currently this attribute is only supported for android.support.v7.widget.Toolbar.
Here is my MainActivity :
public class MainActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getCheckBox();
/*
cb = (CheckBox) super.findViewById(R.id.checkbox);
cb.setOnCheckedChangeListener(this);
*/
}
public void getCheckBox(){
cb = (CheckBox) super.findViewById(R.id.checkbox);
cb.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.getId()==R.id.checkBox){
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(buttonView.getText().toString());
}
}
}
And here my layout :
<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">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My One"
android:id="#+id/checkBox"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="160dp" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Two"
android:id="#+id/checkBox2"
android:layout_alignTop="#+id/checkBox"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView"
android:layout_below="#+id/radioGroup"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="50dp" />
</RelativeLayout>
I get the following exceptions when i run
02-20 15:55:28.130 2110-2110/sqllistviewdemo.wptrafficanalyzer.in.radiobutton E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: sqllistviewdemo.wptrafficanalyzer.in.radiobutton, PID: 2110
java.lang.RuntimeException: Unable to start activity ComponentInfo{sqllistviewdemo.wptrafficanalyzer.in.radiobutton/sqllistviewdemo.wptrafficanalyzer.in.radiobutton.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
at sqllistviewdemo.wptrafficanalyzer.in.radiobutton.MainActivity.getCheckBox(MainActivity.java:34)
at sqllistviewdemo.wptrafficanalyzer.in.radiobutton.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Can you please guide me ? how do you work with checkbox if you don't want to use a button click listener ?
Thanks a lot in advance :)
You are fetching your CheckBox with
findViewById(R.id.checkbox);
when in the xml, the id is
android:id="#+id/checkBox"
The id is case sensitive so check your capitalization. Basically your code is fetching a view by ID and not finding it. Therefore your cb object is set to null and you throw a nullpointer here
cb.setOnCheckedChangeListener(this);
Use MainActivity.this instead of super for getting view from current layout of MainActivity Activity after calling setContentView:
cb = (CheckBox) MainActivity.this.findViewById(R.id.checkBox);
After initializing the checkBox. add this piece of code for eliminating the null reference.
assert checkBox != null;
After washing my face with some freshwater i found that i gave the wrong ID
instead of
R.id.checkBox
i used
R.id.checkbox