Android Text View giving an error when trying to set text - java

I have a layout with few labels and textviews which I want to update based on a action. For testing I have set up the java MainActivity to load the textviews I want to use on created.
Once I click a button called add, the code is executed and prints that the add button was pushed.
I also want the text area to say add for testing. Later on in the project I will change what is displayed here.
However, once I click the button the program stops. I know that the button works because the print shows up in the log.
I have looked and looked and all I can find is the textfield.settext(); But when using this the error occurs and the program stops.
Below is my XML for the TextView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000066"
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.smartshop.MainActivity$PlaceholderFragment" >
<LinearLayout
android1:id="#+id/linearLayout1"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:orientation="vertical" >
<ListView
android1:id="#+id/cartlist"
android1:layout_width="289dp"
android1:layout_height="236dp"
android1:textColor="#color/textc" >
</ListView>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<Button
android1:id="#+id/btnadd"
android1:layout_width="0pt"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:background="#color/buttonc"
android1:onClick="clkaddbutton"
android1:text="Add Item" />
<!-- android1:onClick="clkaddbutton" -->
<android.support.v7.widget.Space
android1:id="#+id/space1"
android1:layout_width="2dp"
android1:layout_height="wrap_content" />
<Button
android1:id="#+id/btnremove"
android1:layout_width="0pt"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:background="#color/buttonc"
android1:onClick="clkremovebutton"
android1:text="Remove Item" />
<!-- android1:onClick = "clkremovebutton" -->
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="#dimen/verticalspacesize">
</View>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<TextView
android1:id="#+id/lblsubtotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="3.40"
android1:text="Sub Total"
android1:textSize="#dimen/textsize"
android1:textColor="#color/textc" />
<TextView
android1:id="#+id/tvsubtotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="3.40"
android1:textSize="#dimen/textsize"
android1:text="TextView" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="#dimen/verticalspacesize">
</View>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<TextView
android1:id="#+id/lbltax"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:text="Tax"
android1:textSize="#dimen/textsize"
android1:textColor="#color/textc" />
<TextView
android1:id="#+id/tvtax"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:textSize="#dimen/textsize"
android1:text="TextView" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="#dimen/verticalspacesize">
</View>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<TextView
android1:id="#+id/lbltotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:text="Total"
android1:textSize="#dimen/textsize"
android1:textColor="#color/textc" />
<TextView
android1:id="#+id/tvtotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:textSize="#dimen/textsize"
android1:text="TextView" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Here is the java code in the MainActivity:
package com.example.smartshop;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
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 android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
import java.lang.*;
public class MainActivity extends ActionBarActivity {
private Button btnadd;
private Button btnremove;
private TextView tfsubtotal ;
private TextView tftax;
private TextView tftotal;
public void clkaddbutton(View view) {
System.out.println("Add clicked");
tfsubtotal.setText("add");
}
public void clkremovebutton(View view) {
tfsubtotal.setText("Rem");
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnremove = (Button) findViewById(R.id.btnremove);
btnadd = (Button) findViewById(R.id.btnadd);
tfsubtotal = (TextView) findViewById(R.id.tvsubtotal);
if(tfsubtotal != null){
System.out.println("The subtotal edittext was created");
tfsubtotal.setText("test" );
}
else{
System.out.println("The textview is null");
}
//tfsubtotal.setText("Google is your friend." );
tftax = (TextView) findViewById(R.id.tvtax);
tftotal = (TextView) findViewById(R.id.tvtotal);
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;
}
}
}
I know that the problem is on the tfsubtotal.setText("add"); line because I have tested without it and everything works.
I have also tried to use edit text boxes instead of textviews but I get the same error.
Can anyone suggest what I might be doing wrong?
Thank you.
Below is the android log:
05-22 22:37:21.251: I/System.out(1693): The subtotal edittext was created
05-22 22:37:21.251: D/AndroidRuntime(1693): Shutting down VM
05-22 22:37:21.261: W/dalvikvm(1693): threadid=1: thread exiting with uncaught exception (group=0xb2accba8)
05-22 22:37:21.271: E/AndroidRuntime(1693): FATAL EXCEPTION: main
05-22 22:37:21.271: E/AndroidRuntime(1693): Process: com.example.smartshop, PID: 1693
05-22 22:37:21.271: E/AndroidRuntime(1693): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.smartshop/com.example.smartshop.MainActivity}: java.lang.NullPointerException
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.os.Handler.dispatchMessage(Handler.java:102)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.os.Looper.loop(Looper.java:136)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-22 22:37:21.271: E/AndroidRuntime(1693): at java.lang.reflect.Method.invokeNative(Native Method)
05-22 22:37:21.271: E/AndroidRuntime(1693): at java.lang.reflect.Method.invoke(Method.java:515)
05-22 22:37:21.271: E/AndroidRuntime(1693): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-22 22:37:21.271: E/AndroidRuntime(1693): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-22 22:37:21.271: E/AndroidRuntime(1693): at dalvik.system.NativeStart.main(Native Method)
05-22 22:37:21.271: E/AndroidRuntime(1693): Caused by: java.lang.NullPointerException
05-22 22:37:21.271: E/AndroidRuntime(1693): at com.example.smartshop.MainActivity.onCreate(MainActivity.java:42)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.Activity.performCreate(Activity.java:5231)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-22 22:37:21.271: E/AndroidRuntime(1693): ... 11 more
05-22 22:37:23.451: I/Process(1693): Sending signal. PID: 1693 SIG: 9

Try this:
public class MainActivity extends ActionBarActivity {
private Button btnadd;
private Button btnremove;
private TextView tfsubtotal ;
private TextView tftax;
private TextView tftotal;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnadd = (Button) findViewById(R.id.btnadd);
System.out.println("The subtotal edittext was created");
//tfsubtotal.setText("Google is your friend." );
tftax = (TextView) findViewById(R.id.tvtax);
TextView tfsubtotal = (TextView) findViewById(R.id.tvsubtotal);
tftotal = (TextView) findViewById(R.id.tvtotal);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void clkaddbutton(View view) {
// tfsubtotal.
System.out.println("Add clicked");
tfsubtotal.setText("add");
}
public void clkremovebutton(View view) {
tfsubtotal.setText("Rem");
}
OR
Why not just do simply like this :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnadd = (Button) findViewById(R.id.btnadd);
Button btnRemove = (Button)findViewById(R.id.btnremove);
tfsubtotal = (TextView) findViewById(R.id.tvsubtotal);
System.out.println("The subtotal edittext was created");
//tfsubtotal.setText("Google is your friend." );
tftax = (TextView) findViewById(R.id.tvtax);
tftotal = (TextView) findViewById(R.id.tvtotal);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
btnadd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
System.out.println("Add clicked");
tfsubtotal.setText("add");
}
});
btnRemove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
System.out.println("Add clicked");
tfsubtotal.setText("Rem");
}
});
}

Related

Fragment TextView ID Causing Crash

I am mainly looking for clarification and advice on this. In the app I am working on I setup a fragment for handling some basic controls and text, and moved the necessary XML from the activities layout file into the fragments layout file, without making any changes. However now when I run the app I get a NULLPOINTEREXCEPTION and it seems to be caused at line 19 in my GameStart activty when I try to set the textView by its ID. I have not changed the ID, only moved it to the fragment layout file, so I have two questions:
1) What exactly is the reason this is happening, because something similar happened before that I resolved but I don't see the reason it was happening in the reference docs on Android Developers
2) Any advice on how to fix this
Below is the GameStart activity, LogCat with the error, and the XML files in question. Thanks in advance, I've spent 2 hours now trying to find this answer.
EDITED FILES/LOGCAT BELOW
LogCat:
12-04 13:48:06.322 826-826/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at com.saphiric.simproject.GameStart.<init>(GameStart.java:25)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
Starting Activity (The error occurs when the app tries to start the GameStart activity):
package com.saphiric.simproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
public class TitleMenu extends ActionBarActivity {
public void startGame(View view){
Intent gameStart = new Intent(this, GameStart.class);
startActivity(gameStart);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
setContentView(R.layout.activity_main_menu);
}
}
Fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Relative layout to handle main interaction area -->
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:layout_alignParentBottom="true"
android:background="#drawable/bg_text">
<TextView
android:id="#id/storyText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="#string/story_opening_one"
android:textColor="#color/black" />
<Button
android:id="#+id/advanceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/controlsFragment"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="#drawable/button_advance"
android:onClick="advanceGame" />
<Button
android:id="#+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#id/advanceButton"
android:background="#drawable/menu_button" />
</RelativeLayout>
</RelativeLayout>
Fragment Class:
package com.saphiric.simproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Saphiric on 12/4/14.
*/
public class ControlsFragment extends Fragment {
/**
* Fragment Lifecycle Methods
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Inflates the layout resource for the fragment
return inflater.inflate(R.layout.controls_fragment, container, false);
}
#Override
public void onPause(){
}
}
GameStart activity:
package com.saphiric.simproject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
/**
* Created by Saphiric on 11/12/14.
*/
public class GameStart extends Activity{
/**
* Necessary activity variables
*/
protected int clickCount = 0;
TextView storyText = (TextView) findViewById(R.id.storyText);
/**
* Sets up and alert dialogue builder for making decisions
* This will need to be revised during production
*/
AlertDialog.Builder decisionTime = new AlertDialog.Builder(getApplicationContext());
/**
* Handles advancing non character based conversations at the beginning
* of the story.
* If the player decides to investigate the scream, then the app loads the appropriate activity, and the same with the
* decision to leave the scene.
*/
public void advanceGame(View view){
clickCount = clickCount + 1; // Increments clickCount by 1 per click
if (clickCount == 1){
storyText.setText(R.string.story_opening_two);
} else if(clickCount == 2){
decisionTime.setTitle("Decision Time!"); // Sets the title for the decision box
decisionTime.setCancelable(false); // Sets it so that the decision can not be cancelled.
decisionTime.setPositiveButton("Investigate",new DialogInterface.OnClickListener() { // Sets up the positive button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
decisionTime.setNegativeButton("Leave the scene.",new DialogInterface.OnClickListener() { // Sets up the negative button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
}
/**
* Android activity methods
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
}
}
GameStart Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<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/bg_school_gate"
android:orientation="vertical">
<fragment
android:id="#+id/controlsFragment"
android:name="com.saphiric.simproject.ControlsFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout="#layout/controls_fragment" />
</RelativeLayout>
No, you don't have any fragment here, read more on How to use fragments.
But that's not your problem it should work the way you did it.
The only problem is that you're calling findViewById in your constructor, or even before that.
findViewById only works if you have a UI, so you must do all UI initialization after setContentView in onCreate!
TextView storyText;
...
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
}
Also don't forget to call show() on decisionTime.
TextView storyText = (TextView) findViewById(R.id.storyText);
This should only be called after you set your contentview.
The final result should be:
TextView storyText;
And then on onCreate
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
1) The reason this is happening is that the view has not yet been instantiated at the time you are trying to get it's reference.
2) How to fix it: if you have a Fragment, then you should get a reference to it's View's in the Fragment.onCreateView() method. Then you can setup the Activity to talk to the Fragment to do whatever changes you need to the View.

Error java.lang.runtimeexception view is not a sliding drawer

Hi I have been creating an app that implements a cutom sliding navigation drawer. However, I keep on receiving an error shown on the title.
Logs:
10-30 15:38:20.510: E/AndroidRuntime(1863): FATAL EXCEPTION: main
10-30 15:38:20.510: E/AndroidRuntime(1863): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobextph.krispykreme/com.mobextph.krispykreme.ParentActivity}: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Handler.dispatchMessage(Handler.java:99)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Looper.loop(Looper.java:137)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invokeNative(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invoke(Method.java:511)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-30 15:38:20.510: E/AndroidRuntime(1863): at dalvik.system.NativeStart.main(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): Caused by: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1170)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.changeFragment(ParentActivity.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.onCreate(ParentActivity.java:111)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Activity.performCreate(Activity.java:5104)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
The Main Activity class is:
package com.mobextph.krispykreme;
import java.util.ArrayList;
import com.mobextph.krispykreme.constants.Constants;
import android.R.color;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
public class ParentActivity extends FragmentActivity {
private Fragment changedFragment= null;
private FragmentManager fm;
private DrawerLayout mDrawerLayout;
private LinearLayout linearLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private ArrayList<String> navDrawerItems;
private ArrayAdapter<String> adapter;
private String[] menuItem= {"ORDER", "STAMP CARD", "REWARDS", "STORES", "FAVORITES"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Drawable d;
// getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
/*Slider*/
mTitle = mDrawerTitle = getTitle();
navMenuTitles= menuItem;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, R.id.title, menuItem));
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.button_menu, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
// changeFragment(-1);
}
fm = getSupportFragmentManager();
// DatabaseHandler db= new DatabaseHandler(this);
//
// for(int i = 0; i < 2; i++){
// db.insertFavorite(Constants.id[i], Constants.imageItem[i],
// Constants.title[i], Constants.price[i], Constants.desc[i],
// Constants.status[i]);
// }
changeFragment(-1);
}
public void changeFragment(int fragment){
FragmentTransaction transaction = fm.beginTransaction();
changedFragment = null;
switch(fragment){
case -1:
changedFragment = new HomeFragment();
// mDrawerLayout.closeDrawers();
break;
case Constants.ORDER_SCREEN_CLICKED:
changedFragment = new OrderFragment();
break;
case Constants.FAVORITES_SCREEN_CLICKED:
changedFragment = new FavoritesFragment();
break;
}
if (changedFragment != null) {
transaction.replace(R.id.fragment_holder, changedFragment);
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
mDrawerList.setItemChecked(fragment, true);
mDrawerList.setSelection(fragment);
mDrawerLayout.closeDrawer(linearLayout);
}
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
int fragment = 0;
if(position == 0)
fragment= Constants.ORDER_SCREEN_CLICKED;
else if(position == 4)
fragment= Constants.FAVORITES_SCREEN_CLICKED;
changeFragment(fragment);
}
}
// #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);
if(mDrawerToggle.onOptionsItemSelected(item))
return true;
switch(item.getItemId()){
default: return super.onOptionsItemSelected(item);
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The view code that shows a linear layout for the sliding drawer and a listview is:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/left_drawer"
android:layout_width="260dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#008265"
android:gravity= "left" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/icon_login"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="LOGIN"
android:textSize="15dp"
android:paddingLeft="5dp"
android:paddingRight="0dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="|"
android:gravity="center"
android:textSize="15dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="SIGN UP"
android:textSize="15dp"
android:paddingLeft="0dp"
android:paddingRight="5dp"/>
</LinearLayout>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:gravity= "left" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Try setting
layout_gravity="start" or layout_gravity="left"
in your left_drawer instead of gravity

Button causing app crash on launch

Hi when I launch my app it crashes instantly reading the logcat I can see that it is cause by the sendButton in my mainActivity, from reading around I people say it has to do with the button not being initiated but as far I can see it is, I have it declared in my fragment_main.xml okay and without the button code in MainActivity.java my code loads the app grand. Any help would really be appreciate.
Logcat
06-20 08:50:18.323: E/AndroidRuntime(30036): FATAL EXCEPTION: main
06-20 08:50:18.323: E/AndroidRuntime(30036): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.draco.dragonmessage/com.draco.dragonmessage.MainActivity}: java.lang.NullPointerException
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2483)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.access$600(ActivityThread.java:178)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.os.Handler.dispatchMessage(Handler.java:107)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.os.Looper.loop(Looper.java:194)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.main(ActivityThread.java:5560)
06-20 08:50:18.323: E/AndroidRuntime(30036): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 08:50:18.323: E/AndroidRuntime(30036): at java.lang.reflect.Method.invoke(Method.java:525)
06-20 08:50:18.323: E/AndroidRuntime(30036): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
06-20 08:50:18.323: E/AndroidRuntime(30036): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
06-20 08:50:18.323: E/AndroidRuntime(30036): at dalvik.system.NativeStart.main(Native Method)
06-20 08:50:18.323: E/AndroidRuntime(30036): Caused by: java.lang.NullPointerException
06-20 08:50:18.323: E/AndroidRuntime(30036): at com.draco.dragonmessage.MainActivity.onCreate(MainActivity.java:48)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.Activity.performCreate(Activity.java:5135)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1151)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
06-20 08:50:18.323: E/AndroidRuntime(30036): ... 11 more
MainActivity.java
package com.draco.dragonmessage;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
String sendMessageString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
final Button sendMessage = (Button) findViewById(R.id.messageButton);
System.out.println(sendMessage.toString());
sendMessage.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
final TextView receivedMessage = (TextView) findViewById(R.id.textReceived);
final EditText messageToSend = (EditText) findViewById(R.id.editTextSend);
sendMessageString = messageToSend.toString();
receivedMessage.setText(sendMessageString);
}
});
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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 {
/**
* 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);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.draco.dragonmessage.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editTextSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/section_label"
android:layout_alignParentBottom="true"
android:ems="10"
android:hint="Enter message to send..." />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/section_label"
android:layout_alignTop="#+id/textReceived"
android:text="Keith"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textReceived"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/section_label"
android:layout_alignRight="#+id/editTextSend"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/messageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editTextSend"
android:layout_alignParentRight="true"
android:layout_marginRight="31dp"
android:text="Button" />
</RelativeLayout>
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.draco.dragonmessage.MainActivity" >
<!--
As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
-->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--
android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead.
-->
<!--
The drawer is given a fixed width in dp and extends the full height of
the container.
-->
<fragment
android:id="#+id/navigation_drawer"
android:name="com.draco.dragonmessage.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start" />
</android.support.v4.widget.DrawerLayout>
Thanks again for any help.
The Button with ID messageButton is in fragment_main.xml. With findByViewById() you are accessing to activity_main.xml (setContentView(R.layout.activity_main);.
You can add an attribute Button to the class and link the element in the onCreateView method of PlaceholderFragment. Then you can access to this button from anywhere in the activity.
Just Move the following lines to Oncreate() and change R.layout to your fragment layout. You are using a wrong layout
final TextView receivedMessage = (TextView) findViewById(R.id.textReceived);
final EditText messageToSend = (EditText) findViewById(R.id.editTextSend);
below this one
final Button sendMessage = (Button) findViewById(R.id.messageButton);

Android app, dynamic activity window with buttons

I am stuck with an idea.
I am trying to implement a feature in a android application.
I have an edittext and a button, if I enter 3 in edittext
and press the button I want to go to another activity which will be having 3 buttons.
If i enter 10 I wanna go to another activity where to display 10 buttons.
I know how to make such switch, I don't know how to do it dynamically ,
I want to make for values between 0 and 10 and I don't want to have 10 fragments .
Plaese give me solution to achieve it ..
Thanks..
Untill now:
mainactivity.java:
package com.example.instances_temperature;
import com.example.instances_temperature.Tabel;
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.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
EditText instances;
Button ok;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ok = (Button) findViewById(R.id.ok);
instances = (EditText) findViewById(R.id.instances);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (instances.getText().toString().length() > 0)
{
int value = Integer.parseInt(instances.getText().toString());;
if(value > 10)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value<0)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value >= 0 && value <=10)
{
schimba(v);
}
}
else
{
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
}
}
});
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;
}
}
public void schimba(View view){
int value = Integer.parseInt(instances.getText().toString());;
Intent intent = new Intent(this, Tabel.class);
intent.putExtra("max", value);
startActivity(intent);
}
}
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.instances_temperature.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/ShowValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Instances No.:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/instances"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<Button
android:id="#+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/instances"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="Ok"
android:onClick="schimba" />
</RelativeLayout>
tabel.java:
package com.example.instances_temperature;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.os.Build;
public class Tabel extends ActionBarActivity {
int i;
int value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabel);
Intent intentObject = getIntent();
value = intentObject.getIntExtra("max", 0);
LinearLayout layout = (LinearLayout)findViewById(R.id.container);
for(i=1;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowview = layoutinflate.inflate( R.layout.ShowMe, null);
TextView showvalue;
showvalue = (TextView) rowview.findViewById(R.id.showid);
showvalue.setText(""+value);
layout.addView(rowview);
}
//showvalue.setText(String.valueOf(getIntent().getExtras().getInt("max")));
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.tabel, 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_tabel,
container, false);
return rootView;
}
}
}
activity_tabel.xml
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.instances_temperature.Tabel"
tools:ignore="MergeRootFrame" >
</LinearLayout>
LinearLayout code of inflation_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/inflationn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ShowMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
LogCat error:
04-24 06:21:04.244: E/AndroidRuntime(269): FATAL EXCEPTION: main
04-24 06:21:04.244: E/AndroidRuntime(269): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.instances_temperature/com.example.instances_temperature.Tabel}: java.lang.NullPointerException
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.os.Looper.loop(Looper.java:123)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-24 06:21:04.244: E/AndroidRuntime(269): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 06:21:04.244: E/AndroidRuntime(269): at java.lang.reflect.Method.invoke(Method.java:521)
04-24 06:21:04.244: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-24 06:21:04.244: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-24 06:21:04.244: E/AndroidRuntime(269): at dalvik.system.NativeStart.main(Native Method)
04-24 06:21:04.244: E/AndroidRuntime(269): Caused by: java.lang.NullPointerException
04-24 06:21:04.244: E/AndroidRuntime(269): at com.example.instances_temperature.Tabel.onCreate(Tabel.java:42)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-24 06:21:04.244: E/AndroidRuntime(269): ... 11 more
You can get the value from the editText by...
String value= EditText.getText().toString();
Pass the value to another activity (Activity2) through Intent
Now in Activity2 you write this code in the onCreate()
for(int i=1 ; i<= value ; i++){
Button b = new Button(getApplicationContext());
LinearLayout.addView(b);
}
Answer to your edited question.....
main xml file activity_table:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
layout file to be inflated layout_inflate:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ShowValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text" />
</LinearLayout>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabel);
Intent intentObject = getIntent();
value = intentObject.getIntExtra("max", 0);
LinearLayout layout= (LinearLayout)findViewById(R.id.layout)
for(i=0;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = layoutinflate.inflate( R.layout.layout_inflate, null);
TextView showvalue;
showvalue = (TextView) rowview.findViewById(R.id.ShowValue);
showvalue.setText(""+value);
layout.addView(rowview);
}
You can retrieve the EditText value on tha Button click. And pass the Value with the intent.
In that Activity you can build your logic Using Swicth cases. Then you can add the number of Buttons dynamically (eg:- for(i=0;i<yourValue;i++) yourValue is got From intent.)

Unfortunately (android app) has stopped.

I am learning android programming using eclipse. I coded a twitter app that simply let's you tweet a status and view a user's timeline. However when I try run the app on my samsung galaxy tab 3.0 the app starts up, all i see is the title at the top, none of the textviews or buttons show up then after 2 seconds the screen goes black and i get the error message ("Unfortunately TwitterApp has stopped") I cant imagine it's something to do with twitter since none of the widgets are being displayed. Here is the code from my main activity, and the activity_main.xml file. And the logCat. Ill even include the manifest
package com.example.twitterapp;
import java.util.List;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView countCharsTV, timelineTV;
EditText usernameET, tweetET;
Button tweetBTN, timelineBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countCharsTV = (TextView) findViewById(R.id.textView1);
timelineTV = (TextView) findViewById(R.id.textView2);
timelineTV.setMovementMethod(new ScrollingMovementMethod());
tweetET = (EditText) findViewById(R.id.editText1);
tweetET.addTextChangedListener(new MyTextWatcher());
usernameET = (EditText) findViewById(R.id.editText2);
tweetBTN = (Button) findViewById(R.id.button1);
tweetBTN.setOnClickListener(tweetBTNOnClickListener);
timelineBTN.setOnClickListener(timelineBTNOnClickListener);
}
//BUTTON CLICK LISTENERS WITHOUT IMPLEMENTS
public OnClickListener tweetBTNOnClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
new MyAsyncTaskTweet().execute(tweetET.getText().toString());
}
};
public OnClickListener timelineBTNOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
new MyAsyncTaskTimeline().execute(timelineTV.getText().toString());
}
};
//END OF BUTTON CLICK LISTENERS
//COUNT CHARS IN TEXTVIEW USING IMPLEMENTS
class MyTextWatcher implements TextWatcher {
#Override
public void afterTextChanged(Editable arg0) {
countCharsTV.setText("" + tweetET.getText().length());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
}
//End OF COUNT CHARS IN TEXTVIEW
//ASYNC TASK CLASSES
//TWEET ASYNC TASK
public class MyAsyncTaskTweet extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... tweet) {
String result = "";
Twitter twitter = TwitterFactory.getSingleton();
try{
twitter.updateStatus(tweet[0]);
result = "Success";
}catch(TwitterException twitterException) {
result = "Failed to update status";
}
return result;
}
#Override
protected void onPostExecute(String result){
tweetET.setHint(result);
tweetET.setText("");
}
}
//END OF TWEET ASYNC TASK
public class MyAsyncTaskTimeline extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... username) {
String result = new String("");
List<twitter4j.Status> statuses = null;
Twitter twitter = TwitterFactory.getSingleton();
try {
statuses = twitter.getUserTimeline(username[0]);
}catch (TwitterException twitterException) {
twitterException.printStackTrace();
}
for(twitter4j.Status status : statuses) {
result += status.getText();
result += "\n";
}
return result;
}
#Override
protected void onPostExecute(String result) {
usernameET.setText("");
timelineTV.setText(result);
}
}
#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;
}
}
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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:text="Tweet" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="Type your tweet here" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText2"
android:layout_alignBottom="#+id/editText2"
android:layout_toLeftOf="#+id/editText2"
android:text="&apos;#" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_toRightOf="#+id/textView1"
android:text="Timeline" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:ems="10"
android:hint="Type a username here" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button2"
android:layout_toRightOf="#+id/button1"
android:text="Timeline will go here" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.twitterapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.twitterapp.MainActivity"
android:label="#string/app_name" >
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat
03-21 22:46:25.117: W/ActivityThread(3806): Application com.example.twitterapp can be
debugged on port 8100...
03-21 22:46:25.289: E/SensorManager(3806): thread start
03-21 22:46:25.296: D/SensorManager(3806): registerListener :: handle = 1598182229
name= BOSCH BMC150 Acceleration Sensor delay= 200000
03-21 22:46:25.296: D/AndroidRuntime(3806): Shutting down VM
03-21 22:46:25.296: W/dalvikvm(3806): threadid=1: thread exiting with uncaught exception
(group=0x40dcd2a0)
03-21 22:46:25.304: E/AndroidRuntime(3806): FATAL EXCEPTION: main
03-21 22:46:25.304: E/AndroidRuntime(3806): java.lang.RuntimeException: Unable to start
activity ComponentInfo{com.example.twitterapp/com.example.twitterapp.MainActivity}:
java.lang.NullPointerException
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2129)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2154)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.access$700(ActivityThread.java:146)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.os.Handler.dispatchMessage(Handler.java:99)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.os.Looper.loop(Looper.java:137)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.main(ActivityThread.java:4949)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
java.lang.reflect.Method.invokeNative(Native Method)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
java.lang.reflect.Method.invoke(Method.java:511)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
dalvik.system.NativeStart.main(Native Method)
03-21 22:46:25.304: E/AndroidRuntime(3806): Caused by: java.lang.NullPointerException
03-21 22:46:25.304: E/AndroidRuntime(3806): at
com.example.twitterapp.MainActivity.onCreate(MainActivity.java:45)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.Activity.performCreate(Activity.java:5185)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
03-21 22:46:25.304: E/AndroidRuntime(3806): ... 11 more
03-21 22:46:38.398: I/Process(3806): Sending signal. PID: 3806 SIG: 9
Where is timelineBTN reference? "timelineBTN" was null.
timelineBTN = (Button)findViewById(R.id.);

Categories

Resources