Converting from Activity to Fragment? Getting Null Pointer Exceptions - java

I'm working on a Madlib app. The code you see below is the class that handles gathering input from edittext boxes found in madlibinput1.xml, storing that info as strings, and then sending that text to the madliboutput.xml where it replaces all "wx" with input gathered in the input xml. This class used to be an activity, but I found making it a fragment helps implement my navigation drawer better. However, I am an almost complete beginner with fragments (and programming in general) and feel like I didn't convert my code to work with fragments very well.
Can someone help me figure out why I have a null pointer exception in the gather() method (and perhaps null pointers elsewhere) when I hit the convert button. Perhaps I am doing something wrong getting information about my xml or something to do with my views. It would be very appreciated thank you.
package com.shamu11.madlibsportable;
import java.io.IOException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
public class Madlibs extends Fragment {
int inLayout; // will hold the id number for layout file
// main_class_activity_in.xml.
int outLayout; // will hold the id number for layout file
// main_class_activity_out.xml.
int outviewid; // will hold the id number for the textview found in
// main_class_activity_out.xml
//Activity activity = this;
String test;
AutoCompleteTextView autoview;
StringBuffer stringbuffer = new StringBuffer();
String[] stringviews = new String[16];
Button convert;
View view;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
view = inflater.inflate(R.layout.madlibinput1, container, false);
//setContentView(R.layout.madlibinput1);
outLayout = (R.layout.madliboutput1);
inLayout = (R.layout.madlibinput1);
outviewid = (R.id.outview14);
convert = (Button) view.findViewById(R.id.convert);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gather();
postIt();
}
});
return view;
}
public void gather() {
ViewGroup layout = (ViewGroup) getView().findViewById(R.id.anskey_clover);
View[] views = new View[layout.getChildCount()];
int[] ids = new int[layout.getChildCount()];
for (int i = 0; i < layout.getChildCount(); i++) {
ids[i] = layout.getChildAt(i).getId();
}
for (int i = 0; i < layout.getChildCount(); i++) {
AutoCompleteTextView au = (AutoCompleteTextView) getActivity().findViewById(ids[i]);
stringbuffer.append(au.getText().toString() + "\n");
}
//setContentView(outLayout);
TextView outview = (TextView) getView().findViewById(outviewid);
outview.setText(stringbuffer.toString());
}
public void postIt() {
String str = "let's go to the park";
String str2;
String newstr = null;
//setContentView(outLayout);
TextView outview = (TextView) view.findViewById(outviewid);
str = (String) outview.getText();
stringviews = stringbuffer.toString().split("\n"); // turns the
// stringbuffer from
// getAllXml() into
// an array and
// assigns to
// stringviews.
for (int i = 0; i < stringviews.length; i++) {
str2 = stringviews[i];
newstr = str.replaceFirst("wx", str2); // replaces all the "wx"s in
// the
// main_class_activity_out
// textview with values from
// strinvgviews.
str = newstr;
}
outview.setText(newstr);
stringbuffer.delete(0, stringbuffer.length());
Fragment newFragment = new MadlibsOutput();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment1, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
madlibinput1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.39"
android:background="#ffffff" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="184dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff" >
<TextView
android:id="#+id/outview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="1.) Adjective to Describe:" />
<TextView
android:id="#+id/lvheader_song"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="2.) ing-verb (i.e. running):" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="3.) Negative Adjective:" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="4.) Negative Verb:" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="5.) Adjective" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="6.) Plural Noun:" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="7.) Verb (ending in &apos;-ed&apos;):" />
</LinearLayout>
<LinearLayout
android:id="#+id/anskey_clover"
android:layout_width="match_parent"
android:layout_height="234dp"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="#+id/auview1"
android:layout_width="141dp"
android:layout_height="wrap_content"
android:layout_weight="0.40"
android:ems="10"
android:text="la dee dah" />
<AutoCompleteTextView
android:id="#+id/auview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
<AutoCompleteTextView
android:id="#+id/auview3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
<AutoCompleteTextView
android:id="#+id/auview4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
<AutoCompleteTextView
android:id="#+id/auview5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
<AutoCompleteTextView
android:id="#+id/auview6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
<AutoCompleteTextView
android:id="#+id/auview7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/convert"
android:layout_width="222dp"
android:layout_height="93dp"
android:layout_weight="0.25"
android:text="Get My Mad Lib" />
</LinearLayout>
madliboutput1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/outview14"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:gravity="left"
android:text="madlib text.........etc" />
</LinearLayout>
LOG CAT:
06-30 23:00:11.530: E/AndroidRuntime(5567): FATAL EXCEPTION: main
06-30 23:00:11.530: E/AndroidRuntime(5567): Process: com.shamu11.madlibsportable, PID: 5567
06-30 23:00:11.530: E/AndroidRuntime(5567): java.lang.NullPointerException
06-30 23:00:11.530: E/AndroidRuntime(5567): at com.shamu11.madlibsportable.Madlibs.gather(Madlibs.java:78)
06-30 23:00:11.530: E/AndroidRuntime(5567): at com.shamu11.madlibsportable.Madlibs$1.onClick(Madlibs.java:51)
06-30 23:00:11.530: E/AndroidRuntime(5567): at android.view.View.performClick(View.java:4438)
06-30 23:00:11.530: E/AndroidRuntime(5567): at android.view.View$PerformClick.run(View.java:18422)
06-30 23:00:11.530: E/AndroidRuntime(5567): at android.os.Handler.handleCallback(Handler.java:733)
06-30 23:00:11.530: E/AndroidRuntime(5567): at android.os.Handler.dispatchMessage(Handler.java:95)
06-30 23:00:11.530: E/AndroidRuntime(5567): at android.os.Looper.loop(Looper.java:136)
06-30 23:00:11.530: E/AndroidRuntime(5567): at android.app.ActivityThread.main(ActivityThread.java:5001)
06-30 23:00:11.530: E/AndroidRuntime(5567): at java.lang.reflect.Method.invokeNative(Native Method)
06-30 23:00:11.530: E/AndroidRuntime(5567): at java.lang.reflect.Method.invoke(Method.java:515)
06-30 23:00:11.530: E/AndroidRuntime(5567): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
06-30 23:00:11.530: E/AndroidRuntime(5567): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
06-30 23:00:11.530: E/AndroidRuntime(5567): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
06-30 23:00:11.530: E/AndroidRuntime(5567): at dalvik.system.NativeStart.main(Native Method)

You try to find view in activity not in fragment, by this line:
AutoCompleteTextView au = (AutoCompleteTextView) getActivity().findViewById(ids[i]);

Related

Could not execute method for android:onClick

I'm making a quiz app and I'm using one EditText, and when I don't type anything in it and press SubmitButton I get this error:
FATAL EXCEPTION: main
Process: com.example.andriod.quiz, PID: 12960
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
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:5264)
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:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
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.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
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:5264)
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:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:284)
at android.widget.TextView.setText(TextView.java:4176)
at com.example.andriod.quiz.MainActivity.submitAnswer(MainActivity.java:65)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
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:5264)
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:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
Here is my java code:
package com.example.andriod.quiz;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
/**
* This app displays Millionaire Quiz
*/
public class MainActivity extends AppCompatActivity {
private String name;
private int correctAnswers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the Ok button is clicked. it's displays personalized greetings.
*
* #param view
*/
public void greetings(View view) {
EditText nameField = (EditText) findViewById(R.id.customer_name);
name = nameField.getText().toString();
TextView greetings = (TextView) findViewById(R.id.greetings);
greetings.setText("Hello " + name + ". Scroll down if you are ready.");
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
LinearLayout questionsLayout = (LinearLayout) findViewById(R.id.questions_layout);
questionsLayout.setVisibility(View.VISIBLE);
}
/**
* Checks correct answers, and displays a toast with congratulations and amount of correctly answered questions.
*
* #param view
*/
public void submitAnswer(View view) {
correctAnswers = 0;
RadioButton firstQuestion = (RadioButton) findViewById(R.id.first_correct);
if (firstQuestion.isChecked()) {
correctAnswers++;
}
EditText secondQuestion = (EditText) findViewById(R.id.second_question);
int answer = Integer.parseInt(secondQuestion.getText().toString());
if (answer == 27) {
correctAnswers++;
}
CheckBox checkBoxA = (CheckBox) findViewById(R.id.answer_a);
CheckBox checkBoxB = (CheckBox) findViewById(R.id.answer_b);
CheckBox checkBoxC = (CheckBox) findViewById(R.id.answer_c);
CheckBox checkBoxD = (CheckBox) findViewById(R.id.answer_d);
if (!checkBoxA.isChecked() && checkBoxB.isChecked() && checkBoxC.isChecked() && !checkBoxD.isChecked()) {
correctAnswers++;
}
RadioButton fourthQuestion = (RadioButton) findViewById(R.id.fourth_correct);
if (fourthQuestion.isChecked()) {
correctAnswers++;
}
RadioButton fifthQuestion = (RadioButton) findViewById(R.id.fifth_correct);
if (fifthQuestion.isChecked()) {
correctAnswers++;
}
String correctlyAnswered;
switch (correctAnswers) {
case 5:
correctlyAnswered = "Congratulation " + name + " you answer correctly to every question! You won 1 million! ";
break;
case 4:
correctlyAnswered = "Congratulation " + name + " you answer correctly to 4 questions! You won 750 thousands! You should try one more time!";
break;
case 3:
correctlyAnswered = "Congratulation " + name + " you answer correctly to 3 questions! You won 500 thousands! You should try one more time!";
break;
case 2:
correctlyAnswered = "Congratulation " + name + " you answer correctly to 3 questions! You won 250 thousands! You should try one more time!";
break;
case 1:
correctlyAnswered = "Congratulation " + name + " you answer correctly to 1 question! You won 100 thousands! You should try one more time!";
break;
default:
correctlyAnswered = "You didn't answer correctly to any question :( \nYou should try one more time!";
}
Toast toast = Toast.makeText(this, correctlyAnswered, Toast.LENGTH_LONG);
toast.show();
}
}
And here is xml file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/second_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#6158AC"
android:orientation="vertical"
tools:context="com.example.andriod.quiz.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:text="Welcome in Millionaire Game! \nAre you ready to play for a million?"
android:textSize="24sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/customer_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Name"
android:inputType="textCapWords" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="greetings"
android:text="Ok"
android:textAllCaps="true" />
</LinearLayout>
<TextView
android:id="#+id/greetings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:paddingTop="16dp"
android:textSize="24sp" />
<LinearLayout
android:id="#+id/questions_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="visible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First question: \nHow many parts has Harry Potter series?" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/first_correct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Seven" /><!--correct-->
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Eight" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Six" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second question: \nOwen thinks of a number, adds 13, and then divides the result by 5. The answer is 8. Find the number Owen thinks of." />
<EditText
android:id="#+id/second_question"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="number"
android:hint="Write here your answer." />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Third question: \nWhat is a value of absolute zero?" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<CheckBox
android:id="#+id/answer_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-189°C" />
<CheckBox
android:id="#+id/answer_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-271,15°C" /><!--correct-->
<CheckBox
android:id="#+id/answer_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0K" /><!--correct-->
<CheckBox
android:id="#+id/answer_d"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100K" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fourth question: \nWhat is the main component in glass?" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/fourth_correct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sand" /> <!--correct-->
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Iron" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Coal" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Water" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fifth question: \nWhich is the largest species of the tiger?" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chinese tiger" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bengali tiger" />
<RadioButton
android:id="#+id/fifth_correct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Siberian tiger" /><!--correct-->
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Indo-Chinese tiger" />
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="submitAnswer"
android:text="Submit answers"
android:textAllCaps="true" />
</LinearLayout>
</LinearLayout>
Does anyone knows why this error occurs?
I'm sorry for every mistake I made, this is my first question here ;)
It fails here:
int answer = Integer.parseInt(secondQuestion.getText().toString());
You must have a not empty field here, and also it should be a number.
You can do simply check:
int answer = 0;
EditText secondQuestion = (EditText) findViewById(R.id.second_question);
if(secondQuestion.getText().toString().equals("")) {
//Handle invalid input
} else {
answer = Integer.parseInt(secondQuestion.getText().toString());
}
Just implement some validation of invalid input, and this can be handled easily.

java.lang.IllegalArgumentException:Duplicate id 0x7f0d00c0, tag null, with another fragment for com.google.android.gms.maps.SupportMapFragment

I am creating list view which contain text view,image and google map.
Code for list view layout:-
<?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="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="45dp"
android:orientation="horizontal"
android:background="#ffffff"
android:paddingLeft="3dp"
android:paddingRight="3dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="3dp"
android:layout_marginTop="3dp"
android:scaleType="fitXY"
android:src="#drawable/profile_pic_bg" />
<TextView
android:id="#+id/textView_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView_time"
android:layout_alignRight="#+id/textView_time"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#0A7692"
android:textSize="15dp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView_username"
android:layout_toRightOf="#+id/imageView1"
android:gravity="left|center"
android:layout_marginLeft="15dp"
android:layout_marginTop="4dp"
android:textColor="#BBB9BC"
android:text=""
android:textSize="13dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="3dp"
android:background="#ffffff"
android:paddingRight="3dp" >
<TextView
android:id="#+id/customtxtmessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:ellipsize="end"
android:maxLines="5"
android:autoLink="web"
android:linksClickable="true"
android:text=""
android:textColor="#000000" />
<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
android:id="#+id/view_pager"
android:layout_marginLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_marginTop="5dp"
android:background="#ffffff"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:visibility="visible" >
</cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager>
</LinearLayout>
<LinearLayout
android:id="#+id/customwall_lin_setwatchlist"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#eef7fa"
android:gravity="center_vertical" >
<TextView
android:id="#+id/customtxtlike"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D56438" />
<ImageView
android:id="#+id/customimgdot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="#drawable/dot_sep" />
<TextView
android:id="#+id/customtxtcomment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Comment"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D56438" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|right" >
<TextView
android:id="#+id/customtxttotallikes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:drawableLeft="#drawable/heart_icon"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D56438" />
<TextView
android:id="#+id/customtxttotalcomments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:drawableLeft="#drawable/comment_icon"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D56438" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/customlayoutgray"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#a3a8aa"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_temp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#a3a8aa"
android:textSize="6sp" />
</LinearLayout>
</LinearLayout>
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="160dp"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Code for List view adapter is:-
/********* Adapter class extends with BaseAdapter and implements with OnClickListener ************/
public class CustomAdapter extends BaseAdapter {
/*********** Declare Used Variables *********/
private FragmentActivity activity;
private ArrayList data;
public ArrayList CommentData;
private static LayoutInflater inflater=null;
public Resources res;
CommonWallBean tempValues=null;
ViewHolder holder;
int i=0;
public static String id="";
String TextOfLike="";
SupportMapFragment mapFragment;
GoogleMap map;
HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
Context con;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Context c,FragmentActivity a, ArrayList d,ArrayList CommentData,Resources resLocal) {
/********** Take passed values **********/
activity = a;
data=d;
res = resLocal;
con=c;
CommentData=CommentData;
/*********** Layout inflator to call external xml layout () ***********/
inflater = ( LayoutInflater )activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView customtxtmessage, customtxttime,customtxttotallikes,textView_time,textView_username
,text_likes;
public ViewPager view_pager;
public ImageView user_image,customimguseravtar;
public TextView textViewLike,customtxtcomment,customtxttotalcomments;
public MapView mapView;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final PagerAdapter adapter;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.wall, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
// holder.customtxttime = (TextView) vi.findViewById(R.id.customtxttime);
holder.textView_username=(TextView)vi.findViewById(R.id.textView_username);
holder.customimguseravtar=(ImageView)vi.findViewById(R.id.imageView1);
holder.textView_time=(TextView)vi.findViewById(R.id.textView_time);
holder.view_pager=(ViewPager)vi.findViewById(R.id.view_pager);
holder.textViewLike=(TextView)vi.findViewById(R.id.customtxtlike);
holder.customtxtmessage=(TextView)vi.findViewById(R.id.customtxtmessage);
holder.customtxttotallikes=(TextView)vi.findViewById(R.id.customtxttotallikes);
holder.customtxtcomment=(TextView)vi.findViewById(R.id.customtxtcomment);
holder.customtxttotalcomments=(TextView)vi.findViewById(R.id.customtxttotalcomments);
mapFragment = (SupportMapFragment) activity.getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
map = mapFragment.getMap();
// Getting reference to the SupportMapFragment
// SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else{
holder=(ViewHolder)vi.getTag();
}
if(position<data.size()){
/***** Get each Model object from Arraylist ********/
// tempValues=null;
tempValues = ( CommonWallBean ) data.get( position );
/************ Set Model values in Holder elements ***********/
holder.textView_time.setText( tempValues.getDate());
holder.textView_username.setText( tempValues.getEmployeeName());
holder.textViewLike.setText(tempValues.getValueOfLike());
holder.customtxtmessage.setText(Html.fromHtml(tempValues.getPostMessage()));
holder.customtxttotallikes.setText(tempValues.getPostLikeCount());
holder.customtxttotalcomments.setText(tempValues.getPostCommentCount());
try {
String url = Const.NewbaseurlPhoto + tempValues.getPhotographFileName();
System.out.println("Thumbnil Url "+url);
Picasso.with(activity).load(url).into(holder.customimguseravtar);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String wallPhotos = tempValues.getWallPhotograph();
String latitude = tempValues.getLatitude();
String longitude = tempValues.getLongitude();
if (latitude != null && !latitude.isEmpty() && !latitude.equals("null")){
holder.view_pager.setVisibility(View.GONE);
String Latitude = tempValues.getLatitude();
String Longitude = tempValues.getLongitude();
//map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Showing / hiding your current location
map.setMyLocationEnabled(false);
// Enable / Disable zooming controls
map.getUiSettings().setZoomControlsEnabled(false);
// Enable / Disable my location button
map.getUiSettings().setMyLocationButtonEnabled(false);
// Enable / Disable Compass icon
map.getUiSettings().setCompassEnabled(false);
// Enable / Disable Rotate gesture
map.getUiSettings().setRotateGesturesEnabled(false);
// Enable / Disable zooming functionality
map.getUiSettings().setZoomGesturesEnabled(false);
MapsInitializer.initialize(con);
// Updates the location and zoom of the MapView
double lat = Double.valueOf("23.012034");
double longi = Double.valueOf("72.510754");
MarkerOptions marker = new MarkerOptions().position(
new LatLng(lat, longi))
.title("Hello Maps");
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
map.addMarker(marker);
//Zoom Particular position
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat,
longi)).zoom(12).build();
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}else {
holder.view_pager.setVisibility(View.GONE);
}
}
return vi;
}
}
}
}
The Log Cat is :
FATAL EXCEPTION: main
Process: com.vervesys.konnect, PID: 26705
android.view.InflateException: Binary XML file line #178: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.vervesys.konnect.adapter.CustomAdapter.getView(CustomAdapter.java:130)
at android.widget.AbsListView.obtainView(AbsListView.java:2255)
at android.widget.ListView.makeAndAddView(ListView.java:1790)
at android.widget.ListView.fillDown(ListView.java:691)
at android.widget.ListView.fillFromTop(ListView.java:752)
at android.widget.ListView.layoutChildren(ListView.java:1630)
at android.widget.AbsListView.onLayout(AbsListView.java:2087)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2013)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1770)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1019)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5725)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #178: Duplicate id 0x7f0d00c0, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2293)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.o
03-18 16:56:08.410 26705-27435/com.vervesys.konnect D/dalvikvm: GC_FOR_ALLOC freed 3139K, 28% free 8554K/11772K, paused 46ms, total 46ms
Please help me to solve this issue, i am not able to figure out what is wrong with this code.
Please help for the same.
Just remove xmlns:android="http://schemas.android.com/apk/res/android"
in this line
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
AND
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
You need have at the end :
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
After struggle a lot for this issue, finally i found that google provides static map in URL.
By using Mapview or fragmentManager will be heavy and app will be slow. so for this better option is to use google static map api.
More details are provided in Android - MapView contained within a Listview and
https://developers.google.com/maps/documentation/staticmaps/
I posted this answer as it may help other.
you can try this line of code in your adapter class for inflating layout
vi = inflater.inflate(R.layout.wall, parent,false);

navigate to another page using the button: Unable to start activity ComponentInfo java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm developing a demo app when i login it will navigate to another page.
Here using button i'm trying to navigate to other page
Main activity
public class WelcomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_welcome);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button ibsignin = (Button) findViewById(R.id.ibsignin);
ibsignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (v.getContext(), Register.class);
startActivity(intent);
}
});
}
}
I have defined button code in xml file still i'm getting null pointer exception.
XML file
<?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="fill_parent"
android:layout_height="fill_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.example.nandan.uschedule.WelcomeActivity"
android:background="#drawable/edit1">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="75dp"
android:id="#+id/welcome"
android:background="#drawable/minnesota"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearLayout"
android:clickable="false"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<EditText
android:layout_width="350dp"
android:layout_height="wrap_content"
android:id="#+id/ibusername"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center"
android:layout_marginBottom="200dp"
android:layout_marginTop="225dp"
android:inputType="textEmailAddress|text"
android:hint="User name/ Email Address"
android:textColor="#000000"
android:textStyle="normal" />
<EditText
android:layout_width="350dp"
android:layout_height="wrap_content"
android:inputType="textPassword|text"
android:ems="10"
android:id="#+id/ibpassword"
android:hint="Password"
android:layout_gravity="center"
android:layout_marginTop="-200dp"
android:textColor="#000000" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remember me"
android:id="#+id/cbRememberme"
android:hint="Remember me"
android:layout_gravity="center" />
<Button
android:layout_width="250dp"
android:layout_height="38dp"
android:text="Sign in"
android:id="#+id/ibsingin"
android:layout_gravity="center"
android:background="#4D306A" />
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Do not have an account yet?"
android:id="#+id/havenoaccount"
android:layout_gravity="center"
android:textColor="#000000"
android:paddingTop="12dp"
android:textSize="20dp" />
<Button
android:layout_width="250dp"
android:layout_height="38dp"
android:text="Sign up"
android:id="#+id/ibsignup"
android:layout_gravity="center"
android:background="#4D306A" />
<TextView
android:layout_width="wrap_content"
android:layout_height="35dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Forgot Password?"
android:id="#+id/ibforgotpwd"
android:layout_gravity="center"
android:textColor="#000000"
android:textSize="20dp"
android:clickable="true" />
</LinearLayout>
</RelativeLayout>
my logcat
Process: com.example.nandan.uschedule, PID: 2487
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nandan.uschedule/com.example.nandan.uschedule.WelcomeActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.nandan.uschedule.WelcomeActivity.onCreate(WelcomeActivity.java:27)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
I don't know which line is 27, but it's most likely the NPE comes from here:
Button ibsignin = (Button) findViewById(R.id.ibsignin);
Make sure your button is in your XML layout and that it is called ibsignin.

Forceclose on Inflating XML

In my app I am adding an identical linearlayout to a linearlayout already on the screen. Here is the code where I try to add it:
LinearLayout addItem=(LinearLayout)findViewById(R.id.lladdItem);
insideScroll.addView(addItem);
I get an Error in LogCat which is posted here:
06-24 14:58:16.873 13304-13304/com.frostbytedev.randomgenie E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.view.ViewGroup.addView(ViewGroup.java:3148)
at android.view.ViewGroup.addView(ViewGroup.java:3131)
at com.frostbytedev.randomgenie.Test.onClick(Test.java:49)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
And the XML that is inflated:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lladdItem"
android:paddingLeft="15dp"
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<TextView
android:layout_weight="10"
android:layout_width="10dp"
android:layout_height="80dp"
android:text="2."
android:id="#+id/tvItem2"/>
<EditText
android:layout_weight="90"
android:layout_width="100dp"
android:layout_height="80dp"
android:hint="List Item 2"
android:id="#+id/etItem2"
android:paddingTop="50dp"/>
</LinearLayout>
XML where it is inflated to:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="465dp"
android:id="#+id/svItems"
android:layout_gravity="center"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="400dp"
android:orientation="vertical"
android:id="#+id/insideScroll">
<LinearLayout
android:paddingLeft="15dp"
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<TextView
android:layout_weight="10"
android:layout_width="10dp"
android:layout_height="80dp"
android:text="1."
android:id="#+id/tvItem1"/>
<EditText
android:layout_weight="90"
android:layout_width="100dp"
android:layout_height="80dp"
android:hint="List Item 1"
android:id="#+id/etItem1"
android:paddingTop="50dp"/>
</LinearLayout>
<LinearLayout
android:paddingLeft="15dp"
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<TextView
android:layout_weight="10"
android:layout_width="10dp"
android:layout_height="80dp"
android:text="2."
android:id="#+id/tvItem2"/>
<EditText
android:layout_weight="90"
android:layout_width="100dp"
android:layout_height="80dp"
android:hint="List Item 2"
android:id="#+id/etItem2"
android:paddingTop="50dp"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_height="50dp"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:weightSum="100">
<Button
android:layout_weight="50"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/bAdd"/>
<Button
android:layout_weight="50"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove"
android:id="#+id/bRemove"
android:layout_gravity="center"/>
</LinearLayout>
</LinearLayout>
Java:
package com.frostbytedev.randomgenie;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Steven on 6/23/13.
*/
public class Test extends Activity implements View.OnClickListener{
java.util.List<TextView> listOfET = new ArrayList<TextView>();
LinearLayout insideScroll;
ScrollView svItems;
TextView etItem1, etItem2;
Button Add, Remove;
int numOfItems = 2, width, height;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamictest);
initialize();
}
private void initialize() {
Add=(Button)findViewById(R.id.bAdd);
Remove=(Button)findViewById(R.id.bRemove);
insideScroll=(LinearLayout)findViewById(R.id.insideScroll);
etItem1=(TextView)findViewById(R.id.etItem1);
etItem2=(TextView)findViewById(R.id.etItem2);
svItems=(ScrollView)findViewById(R.id.svItems);
Add.setOnClickListener(this);
Remove.setOnClickListener(this);
listOfET.add(etItem1);
listOfET.add(etItem2);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.bAdd:
numOfItems += 1;
LinearLayout addItem=(LinearLayout)findViewById(R.id.lladdItem);
insideScroll.addView(addItem);
break;
case R.id. bRemove:
listOfET.remove(numOfItems);
numOfItems -= 1;
break;
}
}
private int getDP(float i) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dp = i;
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);
return pixels;
}
}
Since your code (Test.java:49) is a couple of calls down the stack from the site of the NPE, it's clear that insideScroll is not null there. That leaves addItem as the likely culprit. And the way I read your XML, the call findViewById(R.id.lladdItem) has to return null, because lladdItem is not defined in the XML file that defines your content view (dynamictest.xml).
What I believe you need to do is to inflate lladditem, rather than looking for it where it doesn't exist:
LayoutInflater inflater = LayoutInflater.from(view.getContext());
LinearLayout addItem =
(LinearLayout) inflater.inflate(R.layout.lladditem, null);
insideScroll.addView(addItem);
Correct me if I am wrong, there is a lot to look through, but it looks like the item you are trying to add is in a different xml file than the one that you inflate with setContentView() and I don't see where you inflate that Layout so you would need to do that or that LinearLayout will be null
Now, that can't create a NPE at insideScroll.addView(addItem); and from what I can see it is initialized properly. I would try cleaning your project in case the editor didn't pick up changes to your xml.
Window --> Project --> Clean...
and choose your project

My program crashes when the button is clicked.. why?

LOGCAT
04-03 20:59:46.189: E/AndroidRuntime(362): android.content.res.Resources$NotFoundException: String resource ID #0x0
04-03 20:59:46.189: E/AndroidRuntime(362): at android.content.res.Resources.getText(Resources.java:201)
04-03 20:59:46.189: E/AndroidRuntime(362): at android.widget.TextView.setText(TextView.java:2857)
04-03 20:59:46.189: E/AndroidRuntime(362): at coin.calc.wilson.CoinCalculatorActivity$1.onClick(CoinCalculatorActivity.java:65)
04-03 20:59:46.189: E/AndroidRuntime(362): at android.view.View.performClick(View.java:2485)
04-03 20:59:46.189: E/AndroidRuntime(362): at android.view.View$PerformClick.run(View.java:9080)
04-03 20:59:46.189: E/AndroidRuntime(362): at android.os.Handler.handleCallback(Handler.java:587)
04-03 20:59:46.189: E/AndroidRuntime(362): at android.os.Handler.dispatchMessage(Handler.java:92)
04-03 20:59:46.189: E/AndroidRuntime(362): at android.os.Looper.loop(Looper.java:123)
04-03 20:59:46.189: E/AndroidRuntime(362): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-03 20:59:46.189: E/AndroidRuntime(362): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 20:59:46.189: E/AndroidRuntime(362): at java.lang.reflect.Method.invoke(Method.java:507)
04-03 20:59:46.189: E/AndroidRuntime(362): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-03 20:59:46.189: E/AndroidRuntime(362): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-03 20:59:46.189: E/AndroidRuntime(362): at dalvik.system.NativeStart.main(Native Method)
04-03 20:59:49.720: I/Process(362): Sending signal. PID: 362 SIG: 9
Here is my java code:
package coin.calc.wilson;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class CoinCalculatorActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button solve = (Button)findViewById(R.id.bsolve);
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int td, tc, twenty, ten, five, one, quarter, dime, nickel, penny;
EditText tdet = (EditText)findViewById(R.id.etdollars);
EditText tcet = (EditText)findViewById(R.id.etcents);
try{
td = Integer.parseInt(tdet.getText().toString());
tc = Integer.parseInt(tdet.getText().toString());
}
catch (NumberFormatException e) {
td = tc = 0;
}
if (td < 0 || tc < 0){
/* ERROR */
}
else{
if( td == 0 ){
twenty = ten = five = one = 0;
}
else{
one = td%5;
if(td >= 20){
twenty = (td/20)-((td%20)/20);
}
else{
twenty = 0;
}
int tda20 = td-(20*twenty);
if (tda20 >= 10){
ten = (tda20/10)-((tda20%10)/10);
}
else{
ten = 0;
}
int tda10 = tda20-(10*ten);
if(tda10>=5){
five = (tda10/5)-((tda10%5)/5);
}
else{
five = 0;
}
TextView tv20 = (TextView)findViewById(R.id.tvtwenty);
tv20.setText(twenty);
TextView tv10 = (TextView)findViewById(R.id.tvten);
tv10.setText(ten);
TextView tv5 = (TextView)findViewById(R.id.tvfive);
tv5.setText(five);
TextView tv1 = (TextView)findViewById(R.id.tvone);
tv1.setText(one);
}
if( tc == 0 ){
quarter = dime = nickel = penny = 0;
}
else{
penny = tc%5;
if(tc >= 25){
quarter = (tc/25)-((td%25)/25);
}
else{
quarter = 0;
}
int tcaq = tc-(25*quarter);
if (tcaq >= 10){
dime = (tcaq/10)-((tcaq%10)/10);
}
else{
dime = 0;
}
int tcad = tcaq-(10*ten);
if(tcad>=5){
nickel = (tcad/5)-((tcad%5)/5);
}
else{
nickel = 0;
}
TextView tvq = (TextView)findViewById(R.id.tvquarter);
tvq.setText(quarter);
TextView tvd = (TextView)findViewById(R.id.tvdime);
tvd.setText(dime);
TextView tvn = (TextView)findViewById(R.id.tvnickel);
tvn.setText(nickel);
TextView tvp = (TextView)findViewById(R.id.tvpenny);
tvp.setText(penny);
}
}
}});}
}
and here is the xml:
<TableRow
android:id="#+id/tableRow1"
android:layout_height="wrap_content"
android:gravity="center" >
<EditText
android:id="#+id/etdollars"
android:layout_width="156dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dollars"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
<EditText
android:id="#+id/etcents"
android:layout_width="156dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="cents"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="60dp"
android:gravity="center" >
<Button
android:id="#+id/bsolve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Solve!" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="80dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_weight="0.00"
android:layout_marginLeft="8.75dp"
android:layout_marginRight="8.75dp"
android:src="#drawable/twenty" />
<TextView
android:id="#+id/tvtwenty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:layout_gravity="center_vertical"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="61dp"
android:layout_height="80dp"
android:layout_marginLeft="43dp"
android:layout_marginRight="13.5dp"
android:src="#drawable/cquarter" />
<TextView
android:id="#+id/tvquarter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:layout_gravity="center_vertical"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="80dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_weight="0.00"
android:layout_marginLeft="8.75dp"
android:layout_marginRight="8.75dp"
android:src="#drawable/ten" />
<TextView
android:id="#+id/tvten"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:layout_gravity="center_vertical"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="61dp"
android:layout_height="80dp"
android:layout_marginLeft="43dp"
android:layout_marginRight="13.5dp"
android:src="#drawable/cdime" />
<TextView
android:id="#+id/tvdime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:layout_gravity="center_vertical"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="80dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_weight="0.00"
android:layout_marginLeft="8.75dp"
android:layout_marginRight="8.75dp"
android:src="#drawable/five" />
<TextView
android:id="#+id/tvfive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:layout_gravity="center_vertical"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="61dp"
android:layout_height="80dp"
android:layout_marginLeft="43dp"
android:layout_marginRight="13.5dp"
android:src="#drawable/cnickel" />
<TextView
android:id="#+id/tvnickel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:layout_gravity="center_vertical"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="80dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_weight="0.00"
android:layout_marginLeft="8.75dp"
android:layout_marginRight="8.75dp"
android:src="#drawable/one" />
<TextView
android:id="#+id/tvone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:layout_gravity="center_vertical"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="61dp"
android:layout_height="80dp"
android:layout_marginLeft="43dp"
android:layout_marginRight="13.5dp"
android:src="#drawable/cpenny" />
<TextView
android:id="#+id/tvpenny"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:layout_gravity="center_vertical"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</TableLayout>
If it helps, i think the error MAY have something to do with resources i am using (eight jpgs), but i'm not sure. The program runs cleanly up until the OnClickListener is activated. Thanks for any and all help!
Is here (and in another lines like that):
tv20.setText(twenty);
twenty is int and should be String (I suppose that you want to show the number in the textview):
tv20.setText(String.valueOf(twenty));
EDIT:
All this variables have the same error
int td, tc, twenty, ten, five, one, quarter, dime, nickel, penny;
You have a small but heavy mistake:
If you try to put a number/integer into a TextView, you need to cast it to a String first. If you don't do that, Android things you reference to an internal id like R.string.mynumber and that is not what you want.
try moving the two following lines right underneath Button solve = (Button)findViewById(R.id.bsolve); and before solve.setOnClickListener(new OnClickListener()
EditText tdet = (EditText)findViewById(R.id.etdollars);
EditText tcet = (EditText)findViewById(R.id.etcents);

Categories

Resources