implements OnScrollListener inside listFragment - java

I implemented OnScrollListener interface in ListFragment, and i want to change text when last element of list is visible but it doesn't work. I didn't find example of similar problem(OnScrollListener inside ListFragment). My example:
public class MyListFragment1 extends ListFragment implements OnScrollListener {
public View view;
public class MyListAdapter extends ArrayAdapter<String> {
Context myContext;
List<String> lista;
public MyListAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
myContext = context;
lista = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
LayoutInflater inflater =
(LayoutInflater)myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.row, parent, false);
TextView label=(TextView)row.findViewById(R.id.month);
label.setText(lista.get(position));
ImageView icon=(ImageView)row.findViewById(R.id.icon);
//Customize your icon here
icon.setImageResource(R.drawable.ic_launcher);
return row;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
ListAdapter myListAdapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_1,
month);
setListAdapter(myListAdapter);
*/
List<String> lista = new ArrayList<String>();
lista.add("January");
lista.add("February");
lista.add("March");
lista.add("April");
lista.add("May");
lista.add("June");
lista.add("July");
lista.add("August");
lista.add("September");
lista.add("October");
lista.add("November");
lista.add("December");
MyListAdapter myListAdapter =
new MyListAdapter(getActivity(), R.layout.row, lista);
setListAdapter(myListAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.listfragment1, container, false);
changeText("jestem tutaj");
return view;
}
private void changeText(String txt){
TextView nowy = (TextView)view.findViewById(R.id.article);
nowy.setText(txt);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(
getActivity(),
getListView().getItemAtPosition(position).toString(),
Toast.LENGTH_LONG).show();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (++firstVisibleItem + visibleItemCount > totalItemCount) {
changeText("something");
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
I don't have any error, it just doesn't work ;)
P.S implementation of onScroll method i found in StackOverflow.
EDIT:/ adding logcat:
10-14 01:11:34.944: E/AndroidRuntime(817): FATAL EXCEPTION: main
10-14 01:11:34.944: E/AndroidRuntime(817): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidListFragment/com.exercise.AndroidListFragment.AndroidListFragmentActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.os.Looper.loop(Looper.java:137)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-14 01:11:34.944: E/AndroidRuntime(817): at java.lang.reflect.Method.invokeNative(Native Method)
10-14 01:11:34.944: E/AndroidRuntime(817): at java.lang.reflect.Method.invoke(Method.java:511)
10-14 01:11:34.944: E/AndroidRuntime(817): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-14 01:11:34.944: E/AndroidRuntime(817): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-14 01:11:34.944: E/AndroidRuntime(817): at dalvik.system.NativeStart.main(Native Method)
10-14 01:11:34.944: E/AndroidRuntime(817): Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
10-14 01:11:34.944: E/AndroidRuntime(817): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
10-14 01:11:34.944: E/AndroidRuntime(817): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.Activity.setContentView(Activity.java:1881)
10-14 01:11:34.944: E/AndroidRuntime(817): at com.exercise.AndroidListFragment.AndroidListFragmentActivity.onCreate(AndroidListFragmentActivity.java:11)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.Activity.performCreate(Activity.java:5104)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-14 01:11:34.944: E/AndroidRuntime(817): ... 11 more
10-14 01:11:34.944: E/AndroidRuntime(817): Caused by: java.lang.IllegalStateException: Content view not yet created
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.ListFragment.ensureList(ListFragment.java:386)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.ListFragment.getListView(ListFragment.java:280)
10-14 01:11:34.944: E/AndroidRuntime(817): at com.exercise.AndroidListFragment.MyListFragment1.onCreateView(MyListFragment1.java:93)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.Fragment.performCreateView(Fragment.java:1695)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:861)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1137)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.app.Activity.onCreateView(Activity.java:4717)
10-14 01:11:34.944: E/AndroidRuntime(817): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
10-14 01:11:34.944: E/AndroidRuntime(817): ... 21 more
EDIT 2: I have by tried findViewById but it doesn't work too....

You have implemented the OnScrollListener, but you havent attached it to your ListView.
getListView().setOnScrollListener(this);
add this to your onCreateView Method.

You have this error because you are trying to access your Listview when this one is not created yet.
Caused by: java.lang.IllegalStateException: Content view not yet
created
Your Listview is actually created by the last line of your onCreateView method, at the line which usually look something like this:
return inflater.inflate(R.layout.fragment_list, container, false);
The solution is to access your list from the onActivityCreated method, which is executed just after the onCreateView method.
#Override
public void onActivityCreated (Bundle savedInstanceState){
// Always call the superclass so it can save the view hierarchy state
super.onCreate(savedInstanceState);
getListView().setOnScrollListener(this);
}

Related

How get string values from a custom ListView when its Item is clicked

I have a custom ListView with list item layout as shown
this data is fetched from web service and set to ListView through BaseAdapter, here I provide code of getView() only
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.custom_list_item, null);
holder = new ViewHolder();
holder.desc = (TextView) vi.findViewById(R.id.desc);
holder.day=(TextView)vi.findViewById(R.id.day);
holder.high=(TextView)vi.findViewById(R.id.high);
holder.low=(ImageView)vi.findViewById(R.id.low);
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
if(arrayList.size()<=0)
{
holder.desc.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = ( Weather ) arrayList.get( position );
/************ Set Model values in Holder elements ***********/
holder.desc.setText(tempValues.getDesc());
holder.day.setText("$ "+tempValues.getDay());
holder.high.setText(tempValues.getHigh());
holder.low.setText(tempValues.getLow());
imageLoader.displayImage(arrayList.get(position).getThumbnail(), holder.image,
options, animationListener);
}
return vi;
}
Now the tricky part comes, I want to get Value of desc TextView of custom list item, I tried this way
private AdapterView.OnItemClickListener onItemClickListener(){
AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Weather weather= (Weather) weatherListView.getSelectedItem();
Intent intent = new Intent(ListActivity.this, Detail.class);
intent.putExtra(Detail.WEATHER_DESC, weather.getDesc());
startActivity(intent);
}
};
return onItemClickListener;
}
but at line
intent.putExtra(Detail.WEATHER_DESC, weather.getDesc());
I get error as
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: FATAL EXCEPTION: main
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: java.lang.NullPointerException
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at com.example.weatherservice.ListActivity.onItemClick(ListActivity.java:179)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at android.widget.AdapterView.performItemClick(AdapterView.java:292)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at android.widget.AbsListView$1.run(AbsListView.java:3168)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:605)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4424)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-24 08:36:10.343 1460-1460/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
I have searched SO but no answer satisfies my requirement.
private AdapterView.OnItemClickListener onItemClickListener(){
AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Weather weather= (Weather) weatherListView.getSelectedItem(); // instead of this
Intent intent = new Intent(ListActivity.this, Detail.class);
Weather weather= (Weather) adapterView.getItem(i); // use this
intent.putExtra(Detail.WEATHER_DESC, weather.getDesc());
startActivity(intent);
}
};
return onItemClickListener;
}
You have an ArrayList already and onItemClick of the ListView you are getting the position of the the item clicked, so you should do it like this.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Weather weather= (Weather) arrayList.get(i); // i is the position of item clicked.
Intent intent = new Intent(ListActivity.this, Detail.class);
intent.putExtra(Detail.WEATHER_DESC, weather.getDesc());
startActivity(intent);
}
};
I think the problem come from your approach. I suggest you do it another way:
//create getWeather function in your adapter
public Weather getWeather(int position){
// do something like: return arryList.get(position)
}
// In your activity, set OnItemCLickListener for your listview:
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Weather weather = yourAdapter.getWeather(i);//use your adapter to get weather
}
});

Null Pointer Exception while setting value of TextView in an Array Adapter class - Android

I'm getting a NullPointerException while trying to start an Activity which contains a ListView .
In the getView method of the adapter class, the exception happens when the setText function of a textView is being called .
The code bellow is my adapter class:
public class QuestionsListAdapter extends ArrayAdapter<Question> {
Context context;
List<Question> questions;
public QuestionsListAdapter(Context context, List<Question> questions){
super(context, R.layout.list_item_question, questions);
this.context = context;
this.questions = questions;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = vi.inflate(R.layout.list_item_question, null);
Question question = questions.get(position);
TextView tv = (TextView) view.findViewById(R.id.question_list_item_string);
Log.i(TableCreator.LOG_TAG, question.toString()); //this works fine and the string is not null .
tv.setText(question.toString()+""); //NULL POINTER EXCEPTION .
return view;
}
}
As you see, I've logged the string in the logcat and it works just fine, but the next line makes the mistake .
And this is the logcat output:
05-27 13:24:02.979 5325-5325/org.kabiri.operationcheklist I/Operation Checklist﹕ |-Question-> id:1 summary:mySummary comment:myComment solution:mySolution ownerList:dummyOwner
05-27 13:24:02.979 5325-5325/org.kabiri.operationcheklist D/AndroidRuntime﹕ Shutting down VM
05-27 13:24:02.979 5325-5325/org.kabiri.operationcheklist W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0f5f648)
05-27 13:24:02.979 5325-5325/org.kabiri.operationcheklist E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at org.kabiri.operationchecklist.adapter.QuestionsListAdapter.getView(QuestionsListAdapter.java:43)
at android.widget.AbsListView.obtainView(AbsListView.java:2177)
at android.widget.ListView.makeAndAddView(ListView.java:1840)
at android.widget.ListView.fillDown(ListView.java:675)
at android.widget.ListView.fillFromTop(ListView.java:736)
at android.widget.ListView.layoutChildren(ListView.java:1655)
at android.widget.AbsListView.onLayout(AbsListView.java:2012)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
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:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:502)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
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:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1976)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1730)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
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)
The logcat shows that the error happens on this line of my adapter class:
tv.setText(question.toString()+"");
I really appreciate your help .
You already know where the problem is!
tv.setText(question.toString()+"");
is causing the NPE that means the TextView tv is null. And that means that the line
TextView tv = (TextView) view.findViewById(R.id.question_list_item_string);
is not able to find the TextView. Check the question_list_item_string id and make sure it matches the id in your list_item_question.xml file

java.lang.runtimeexception unable to start activity componentinfo java.lang.nullpointerexception android

im making a simple calories calculator and it gives me that error, i already reviewed the code and searched here for the solution but im not able to see why is not running.
I thought it was because i had not initialized the variable, so i did it and still got the same error, maybe is something with the spinners, im new on using spinners
here is the code:
public class CaloriesCalculator extends ActionBarActivity {
EditText etAge, etWeight, etHeight;
Button btnCalculate;
TextView tvResult;
Spinner spinnerGender, spinnerActivity;
String itemGender, itemActivity;
int Height=0;
int Weight=0;
int Age=0;;
double bmr=0.0;
double tdee=0.0;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.caloriescalculator);
spinnerGender=(Spinner)findViewById(R.id.spinnerGender);
spinnerActivity=(Spinner)findViewById(R.id.spinnerActivity);
etAge=(EditText)findViewById(R.id.etAge);
etWeight=(EditText)findViewById(R.id.etWeight);
etHeight=(EditText)findViewById(R.id.etHeight);
tvResult=(TextView)findViewById(R.id.tvResult);
List<String> list = new ArrayList<String>();
list.add("Male");
list.add("Female");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(dataAdapter);
List<String> list2 = new ArrayList<String>();
list.add("Sedentary");
list.add("Lightly Active");
list.add("Moderalety Active");
list.add("Very Active");
list.add("Extremely Active");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list2 );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerActivity.setAdapter(dataAdapter2);
btnCalculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
spinnerGender.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
spinnerActivity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
itemGender=String.valueOf(spinnerGender.getSelectedItem());
itemActivity=String.valueOf(spinnerActivity.getSelectedItem());
if(itemGender=="Male"){
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.9;
}
}
else if(itemGender=="Female") {
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.9;
}
}
result=Double.toString(tdee);
tvResult.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;
}
#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);
}
}
logcat:
11-28 17:20:05.501: E/AndroidRuntime(1455): FATAL EXCEPTION: main
11-28 17:20:05.501: E/AndroidRuntime(1455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Looper.loop(Looper.java:137)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:20:05.501: E/AndroidRuntime(1455): at dalvik.system.NativeStart.main(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): Caused by: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:67)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:20:05.501: E/AndroidRuntime(1455): ... 11 more
11-28 17:24:42.341: D/AndroidRuntime(1507): Shutting down VM
11-28 17:24:42.341: W/dalvikvm(1507): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-28 17:24:42.371: E/AndroidRuntime(1507): FATAL EXCEPTION: main
11-28 17:24:42.371: E/AndroidRuntime(1507): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Looper.loop(Looper.java:137)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:24:42.371: E/AndroidRuntime(1507): at dalvik.system.NativeStart.main(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): Caused by: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:70)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:24:42.371: E/AndroidRuntime(1507): ... 11 more
Yout btnCalculate is null, you should initialize before doing the onclickListener:
btnCalculate = (Button)findViewById(R.id.btnCalculate); //your id
Also note that you are initializing the dataAdapter2 but actually you are using dataAdapert, and list2 dont have any elements, because you declare it but u are filling always list1

Dialog crashing when TextView set

I have the following code which is called by the onClick event of buttons contained within a ListView.
public void viewExerciseHistory(View view) {
// History button click handler
LinearLayout parentRow = (LinearLayout)view.getParent();
TextView exerciseNameTextView = (TextView)parentRow.getChildAt(0);
String exerciseName = (String)exerciseNameTextView.getText();
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.exercise_history_dialog);
dialog.setTitle(exerciseName);
TextView headerTextView = (TextView)view.findViewById(R.id.exercise_history_dialog_name_textview);
//headerTextView.setText("History");
Button closeDialogButton = (Button)view.findViewById(R.id.exercise_history_dialog_close_button);
//closeDialogButton.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View v) {
// dialog.dismiss();
// }
//});
dialog.show();
}
The ListView row is defined as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView android:id="#+id/exercise_history_dialog_name_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:typeface="monospace"
android:textSize="15sp" />
<Button android:id="#+id/exercise_history_dialog_close_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:typeface="monospace"
android:textSize="12sp"
android:textColor="#color/button_blue_text"
android:text="#string/button_text_close"
style="?android:attr/borderlessButtonStyle" />
</RelativeLayout>
The above code works fine and displays the dialog, but if uncomment out the headerTextView.setText("History") or the closeDialog.setOnClickListener it crashes with a NullPointerException.
Can anyone explain what I'm doing wrong?
EDIT LogCat:
10-14 21:36:19.755: W/IInputConnectionWrapper(26167): getTextBeforeCursor on inactive InputConnection
10-14 21:36:19.755: W/IInputConnectionWrapper(26167): getTextAfterCursor on inactive InputConnection
10-14 21:36:19.915: W/IInputConnectionWrapper(26167): getTextBeforeCursor on inactive InputConnection
10-14 21:36:19.945: W/IInputConnectionWrapper(26167): getTextAfterCursor on inactive InputConnection
10-14 21:36:20.435: D/AndroidRuntime(26167): Shutting down VM
10-14 21:36:20.435: W/dalvikvm(26167): threadid=1: thread exiting with uncaught exception (group=0x40e27930)
10-14 21:36:20.445: E/AndroidRuntime(26167): FATAL EXCEPTION: main
10-14 21:36:20.445: E/AndroidRuntime(26167): java.lang.IllegalStateException: Could not execute method of the activity
10-14 21:36:20.445: E/AndroidRuntime(26167): at android.view.View$1.onClick(View.java:3599)
10-14 21:36:20.445: E/AndroidRuntime(26167): at android.view.View.performClick(View.java:4204)
10-14 21:36:20.445: E/AndroidRuntime(26167): at android.view.View$PerformClick.run(View.java:17355)
10-14 21:36:20.445: E/AndroidRuntime(26167): at android.os.Handler.handleCallback(Handler.java:725)
10-14 21:36:20.445: E/AndroidRuntime(26167): at android.os.Handler.dispatchMessage(Handler.java:92)
10-14 21:36:20.445: E/AndroidRuntime(26167): at android.os.Looper.loop(Looper.java:137)
10-14 21:36:20.445: E/AndroidRuntime(26167): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-14 21:36:20.445: E/AndroidRuntime(26167): at java.lang.reflect.Method.invokeNative(Native Method)
10-14 21:36:20.445: E/AndroidRuntime(26167): at java.lang.reflect.Method.invoke(Method.java:511)
10-14 21:36:20.445: E/AndroidRuntime(26167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-14 21:36:20.445: E/AndroidRuntime(26167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-14 21:36:20.445: E/AndroidRuntime(26167): at dalvik.system.NativeStart.main(Native Method)
10-14 21:36:20.445: E/AndroidRuntime(26167): Caused by: java.lang.reflect.InvocationTargetException
10-14 21:36:20.445: E/AndroidRuntime(26167): at java.lang.reflect.Method.invokeNative(Native Method)
10-14 21:36:20.445: E/AndroidRuntime(26167): at java.lang.reflect.Method.invoke(Method.java:511)
10-14 21:36:20.445: E/AndroidRuntime(26167): at android.view.View$1.onClick(View.java:3594)
10-14 21:36:20.445: E/AndroidRuntime(26167): ... 11 more
10-14 21:36:20.445: E/AndroidRuntime(26167): Caused by: java.lang.NullPointerException
10-14 21:36:20.445: E/AndroidRuntime(26167): at com.example.workoutlog.ManageWorkouts.viewExerciseHistory(ManageWorkouts.java:269)
10-14 21:36:20.445: E/AndroidRuntime(26167): ... 14 more
It's crashing because this line:
TextView headerTextView = (TextView) findViewById(R.id.exercise_history_dialog_name_textview);
is actually returning null.
The findViewById method is looking for the view on the main activity's content view. Instead you want to use the findViewById method on the view object. Calling findViewById on the view object will allow you to get the fields you are after.
dialog.setContentView(R.layout.exercise_history_dialog);
TextView headerTextView = (TextView) dialog.findViewById(R.id.exercise_history_dialog_name_textview);
headerTextView.setText("History");
Try changing these
TextView headerTextView = (TextView)findViewById(R.id.exercise_history_dialog_name_textview);
Button closeDialogButton = (Button)findViewById(R.id.exercise_history_dialog_close_button);
to
TextView headerTextView = (TextView)dialog.findViewById(R.id.exercise_history_dialog_name_textview);
Button closeDialogButton = (Button)dialog.findViewById(R.id.exercise_history_dialog_close_button);
You have to tell which view you want to findViewById from

Creating a ListView with custom list items programmatically in Android - no xml list item layout

As I have seen on previously asked questions, inside the custom adapter class (say, MyAdapter extends ArrayAdapter) they always use an inflated xml list-item layout. What I am hoping to do is create everything entirely using Java and no XML...
// for example
String[] wordlist = new String[] {a, b, c};
LinearLayout list_item_layout = new LinearLayout(this);
list_item_layout.setId(5000);
TextView listText = new TextView(this);
listText.setId(5001);
listLayout.addView(listText);
ListView list = new ListView(this);
// ** QUESTION ** do I declare a programmatic .setAdapter() like this?
// ** TAKE NOTE ** I passed 'wordlist' here..
list.setAdapter(new MyAdapter(this, list_item_layout.getId(), listText.getId(), wordlist));
and then for MyAdapter...
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource, int textViewResourceId, String[] strings) {
super(context, resource, textViewResourceId, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView; //is this the list_item_layout that I passed??
TextView tv = (TextView) v.findViewById(5001);
// ** QUESTION ** do I pass 'wordlist' again here?
tv.setText( wordlist[position] );
return v;
}
}
What happens when I run this on my device is I get the following errors...
10-08 23:11:19.775: E/AndroidRuntime(18276): FATAL EXCEPTION: main
10-08 23:11:19.775: E/AndroidRuntime(18276): android.content.res.Resources$NotFoundException: String resource ID #0x0
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.content.res.Resources.getText(Resources.java:222)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.widget.TextView.setText(TextView.java:3011)
10-08 23:11:19.775: E/AndroidRuntime(18276): at com.turista.client.TuristaClientMain.onClick(TuristaClientMain.java:113)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.view.View.performClick(View.java:2538)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.view.View$PerformClick.run(View.java:9152)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.os.Handler.handleCallback(Handler.java:587)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.os.Handler.dispatchMessage(Handler.java:92)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.os.Looper.loop(Looper.java:123)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.app.ActivityThread.main(ActivityThread.java:3691)
10-08 23:11:19.775: E/AndroidRuntime(18276): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 23:11:19.775: E/AndroidRuntime(18276): at java.lang.reflect.Method.invoke(Method.java:507)
10-08 23:11:19.775: E/AndroidRuntime(18276): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
10-08 23:11:19.775: E/AndroidRuntime(18276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
10-08 23:11:19.775: E/AndroidRuntime(18276): at dalvik.system.NativeStart.main(Native Method)
Can anyone explain how to do this programmatically?
* EDITED * October 9, 2012
Ok, as I am still stuck in this issue I think I've made some improvements but still get error messages. The improved code is as follows..
//wordlist is a global variable
String[] wordlist = new String[] {a, b, c};
// ..
// .. inside onCreate...
ListView list = new ListView(this);
list.setAdapter(new MyAdapter(this, R.layout.listitem, R.id.mLargeTextView, wordlist));
// since the ArrayAdapter class needs XML parameters to inflate, I created a dummy layout
now inside MyAdapter class..
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource, int textViewResourceId, String[] strings) {
super(context, resource, textViewResourceId, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = new LinearLayout(Main.this);
listLayout.setLayoutParams(new LayoutParams(wrapContent, wrapContent));
listLayout.setId(5000);
TextView listText = new TextView(Main.this);
listText.setId(5001);
listLayout.addView(listText);
listText.setText(wordlist[position]);
return listLayout;
}
}
As you can see, I think I have to override getView in order to display my custom view so this is what I did. Unfortunately I think I misunderstood it. Here are the errors..
10-09 09:24:10.095: E/AndroidRuntime(2517): FATAL EXCEPTION: main
10-09 09:24:10.095: E/AndroidRuntime(2517): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.ListView.measureScrapChild(ListView.java:1183)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.ListView.measureHeightOfChildren(ListView.java:1266)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.ListView.onMeasure(ListView.java:1175)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
10-09 09:24:10.095: E/AndroidRuntime(2517): at com.android.internal.widget.WeightedLinearLayout.onMeasure(WeightedLinearLayout.java:60)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewRoot.performTraversals(ViewRoot.java:847)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewRoot.handleMessage(ViewRoot.java:1868)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.os.Handler.dispatchMessage(Handler.java:99)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.os.Looper.loop(Looper.java:123)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.app.ActivityThread.main(ActivityThread.java:3691)
10-09 09:24:10.095: E/AndroidRuntime(2517): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 09:24:10.095: E/AndroidRuntime(2517): at java.lang.reflect.Method.invoke(Method.java:507)
10-09 09:24:10.095: E/AndroidRuntime(2517): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
10-09 09:24:10.095: E/AndroidRuntime(2517): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
10-09 09:24:10.095: E/AndroidRuntime(2517): at dalvik.system.NativeStart.main(Native Method)
ListView extends AbsListView which in turn extends AdapterView which extends view group. So all the child of ListView would be added to ViewGroup. So to set the layout param, you can
use ViewGroup.LayoutParam while setting layout param for listLayout.
Or try AbsListView.LayoutParams for setting layout param for listLayout
Please try it and let me know if it worked.
Following code is working fine..
public class MainActivity1 extends Activity {
String[] wordlist = new String[] { "a", "b", "c" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = new ListView(this);
list.setAdapter(new MyAdapter(this, wordlist));
setContentView(list);
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, String[] strings) {
super(context, -1, -1, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = new LinearLayout(MainActivity1.this);
listLayout.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.WRAP_CONTENT,
AbsListView.LayoutParams.WRAP_CONTENT));
listLayout.setId(5000);
TextView listText = new TextView(MainActivity1.this);
listText.setId(5001);
listLayout.addView(listText);
listText.setText(super.getItem(position));
return listLayout;
}
}
}
The problem was that by default Eclipse imports ViewGroup.LayoutParams which are incompatible with the AbsListView.LayoutParams which need to be used for setting layout param for view returned from the getView() method.
Please check and let me know how it went..
To add to the above answer, setting id with a constant number is not a good idea.
Replace, listLayout.setId(5000); with,listLayout.setId(View.generateViewId());
In case you are targeting API 16 and below, refer this.

Categories