Sorry if I may sound stupid; I'm new to Android. I've checked other SO posts with similar problems, but nothing is helping me. I'm making a custom ArrayAdapter, but a NullPointerException is being thrown when the adapter is set to to the list. Here's the fragment XML layout (fragment_lines) with the list:
<?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">
<ListView
android:id="#+id/lines_list_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Here's the list item layout (lines_list_item):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="16dp"
android:id="#+id/line_icon"
android:background="#drawable/red_circle"
/>
<TextView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/line_letter"
android:text = "R"
android:textColor="#FFFFFF"
android:gravity="center"
android:textSize="25sp"
android:layout_marginTop="16dp"
android:layout_marginLeft="-56dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="#+id/line_name"
android:text = "Red Line"
android:textSize="16sp"
android:textColor="#000000"
android:gravity="center"
android:layout_marginTop="13dp"
android:layout_marginLeft="16dp"
/>
</LinearLayout>
Here's the custom ArrayAdapter class (LineAdapter):
package com.example.android.testapp;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* Created by Shubhang on 2/16/2015.
*/
public class LineAdapter extends ArrayAdapter<String> {
Activity context;
int[] icons;
String[] letters;
String[]lines;
String[] letterColors;
public LineAdapter(Activity context, int[] icons, String[] letters, String[] lines, String[] letterColors) {
super(context, R.layout.lines_list_item, letters);
this.context = context;
this.icons = icons;
this.letters = letters;
this.lines = lines;
this.letterColors = letterColors;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.lines_list_item, null);
}
View icon = rowView.findViewById(R.id.line_icon);
TextView letter = (TextView) rowView.findViewById(R.id.line_letter);
TextView line = (TextView) rowView.findViewById(R.id.line_name);
icon.setBackgroundResource(icons[position]);
letter.setText(letters[position]);
line.setText(lines[position]);
letter.setTextColor(Color.parseColor(letterColors[position]));
return rowView;
}
}
Finally, here's the MainActivity:
package com.example.android.testapp;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.example.android.testapp.data.SubwayContract;
import com.example.android.testapp.data.SubwayProvider;
import com.example.android.testapp.sync.CommuterSyncAdapter;
import com.google.transit.realtime.GtfsRealtime;
import java.io.IOException;
import java.net.URL;
public class MainActivity extends ActionBarActivity {
SubwayProvider provider;
Account mAccount;
private static final String LOG_TAG = CommuterSyncAdapter.class.getSimpleName();
int[] icons = {R.drawable.red_circle, R.drawable.blue_circle, R.drawable.brown_circle, R.drawable.green_circle,
R.drawable.orange_circle, R.drawable.purple_circle, R.drawable.pink_circle, R.drawable.yellow_circle};
String[] letters = {"R", "B", "B", "G", "O", "P", "P", "Y"};
String[] lines = {"Red Line", "Blue Line", "Brown Line", "Green Line", "Orange Line", "Purple Line", "Pink Line", "Yellow Line"};
String[] letterColors = {"#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#000000"};
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new LinesFragment())
.commit();
}
LineAdapter adapter = new LineAdapter(MainActivity.this, icons, letters, lines, letterColors);
list = (ListView) findViewById(R.id.lines_list_view);
list.setAdapter(adapter);
...
}
...
}
The stack trace is telling me that there's a NullPointerException on line 51 of MainActivity (this line: list.setAdapter(adapter);). I've combed through LineAdapter and can't seem to find anything wrong. Can someone please help?
Thanks in advance.
I think you are confusing fragments and layouts.
Your setContentView is loading this XML file activity_main
And seems like the ListView lines_list_view is in fragment_lines
So, fix that part, add that ListView to you activity_main or set fragment_lines as your ContentView and check again.
LineAdapter adapter = new LineAdapter(MainActivity.this, icons, letters, lines, letterColors);
list = (ListView) findViewById(R.id.lines_list_view);
list.setAdapter(adapter);
Try moving this code to onCreateView() of the fragment instead of here and if that works,read about the fragment lifecycle
Related
I have an android application and i want to display database data in one of the activity in a listview. I already managed to display it in a listview on a fragment, but now i want to apply the same process to an activity.
I already tried to take the code i used to display data on my fragment, and use it for my activity, but didn't work even after making some change, and i'm still getting an error on #Override.
Here is my activity code :
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.schoolapp.DBHelper;
import com.example.schoolapp.R;
import java.util.ArrayList;
import java.util.HashMap;
public class AdminEvenementActivity3 extends AppCompatActivity {
private TextView Date;
DBHelper SchoolDB;
String CONTENU_ANG;
String CONTENU_ANG_DATE;
HashMap<String,String> user;
ListView CDCANGList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_evenement3);
Date = (TextView) findViewById(R.id.Date);
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
Date.setText(date);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_cdc_ang, container, false);
CDCANGList = rootView.findViewById(R.id.CDCANGList);
SchoolDB = new DBHelper(AdminEvenementActivity3.this);
SQLiteDatabase db = SchoolDB.getReadableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
Cursor view = db.rawQuery("SELECT CONTENU_ANGLAIS_DATE, CONTENU_ANGLAIS FROM CONTENU_COURS_ANGLAIS", null);
if (view.moveToFirst()){
do {
// Passing values
user = new HashMap<>();
CONTENU_ANG = view.getString(view.getColumnIndex("CONTENU_ANGLAIS"));
CONTENU_ANG_DATE = view.getString(view.getColumnIndex("CONTENU_ANGLAIS_DATE"));
user.put("Contenu",CONTENU_ANG);
user.put("Date",CONTENU_ANG_DATE);
userList.add(user);
} while(view.moveToNext());
Log.d("Contenu",userList.toString());
Log.d("Date",userList.toString());
ListAdapter adapter = new SimpleAdapter(AdminEvenementActivity3.this, userList, R.layout.cdcangrow,new String[]{"Contenu", "Date"}, new int[] .
{R.id.ContenuANG, R.id.ContenuANGDate});
CDCANGList.setAdapter(adapter);
}
view.close();
db.close();
return rootView;
}
}```
Here is my layout holding the listview :
```<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/CDCANGList"/>
</RelativeLayout>```
And here is my layout for the arrangement of each row of the listview :
```<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/ContenuANG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/textView3"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ContenuANGDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:layout_marginTop="24dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/textView7"
app:layout_constraintTop_toBottomOf="#+id/ContenuANG" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:drawableLeft="#drawable/ic_histgeo"
android:text="Travail effectuer :"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="72dp"
android:layout_marginLeft="72dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="152dp"
android:layout_marginRight="152dp"
android:text="Date : "
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>```
I'm expecting each row of the table to display in the listview of my activity. I'm getting the following error message caused by the "#Override" : "error: method does not override or implement a method from a supertype".
'onCreateView() method is only for fragment it cannot be override in activity.'
put you all the code in onCreate() method of your activity. it will be working pretty fine Thanks
if you feel any other problem please discuss
Thanks you a lot for your answer! I did the modification, but now i'm having some troubles on my layout inflater and my retur rootView. Any ideas how i could correct this? See my code below.
package com.example.schoolapp.Admin;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.schoolapp.DBHelper;
import com.example.schoolapp.R;
import java.util.ArrayList;
import java.util.HashMap;
public class AdminEvenementActivity3 extends AppCompatActivity {
private TextView Date;
DBHelper SchoolDB;
String CONTENU_ANG;
String CONTENU_ANG_DATE;
HashMap<String,String> user;
ListView CDCANGList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_evenement3);
Date = (TextView) findViewById(R.id.Date);
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
Date.setText(date);
final View rootView = inflater.inflate(R.layout.fragment_cdc_ang, container, false);
CDCANGList = rootView.findViewById(R.id.CDCANGList);
SchoolDB = new DBHelper(AdminEvenementActivity3.this);
SQLiteDatabase db = SchoolDB.getReadableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
Cursor view = db.rawQuery("SELECT CONTENU_ANGLAIS_DATE, CONTENU_ANGLAIS FROM CONTENU_COURS_ANGLAIS", null);
if (view.moveToFirst()){
do {
// Passing values
user = new HashMap<>();
CONTENU_ANG = view.getString(view.getColumnIndex("CONTENU_ANGLAIS"));
CONTENU_ANG_DATE = view.getString(view.getColumnIndex("CONTENU_ANGLAIS_DATE"));
user.put("Contenu",CONTENU_ANG);
user.put("Date",CONTENU_ANG_DATE);
userList.add(user);
} while(view.moveToNext());
Log.d("Contenu",userList.toString());
Log.d("Date",userList.toString());
ListAdapter adapter = new SimpleAdapter(AdminEvenementActivity3.this, userList, R.layout.cdcangrow,new String[]{"Contenu", "Date"}, new int[]{R.id.ContenuANG, R.id.ContenuANGDate});
CDCANGList.setAdapter(adapter);
}
view.close();
db.close();
return rootView;
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to create an app that introduces attractions of los angeles and restaurants of los angeles. The main page is a image of attraction and restaurant, when you click either one it will opens up more attraction or restaurant for people to read about the details. I am implementing listview, however my setadapter is not working. Please take a look at my code and help a newbie out! Thanks! The error code is as below and the codes of my program after that.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
MainActivity.java:
package com.example.android.tourguide;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void attractionList(View v) {
Intent intent = new Intent(this, attractionList.class);
startActivity(intent);
}
}
attractionList.java:
package com.example.android.tourguide;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class attractionList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_list);
ArrayList<Attraction> attractionArrayList = new ArrayList<>();
attractionArrayList.add(new Attraction(R.drawable.griffith, R.raw.attraction, "Griffith Observatory"));
AttractionAdapter attractionAdapter = new AttractionAdapter(this, attractionArrayList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(attractionAdapter);
}
}
AttractionAdapter.java:
package com.example.android.tourguide;
import android.content.Context;
import android.content.res.AssetManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class AttractionAdapter extends ArrayAdapter<Attraction> {
private ArrayList<Attraction> mArrayList = new ArrayList<>();
private Context mContext;
private String eachline;
public AttractionAdapter(Context context, ArrayList<Attraction> arrayList){
super(context,0, arrayList);
mArrayList = arrayList;
mContext = context;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listView = convertView;
if (listView == null) {
listView = LayoutInflater.from(mContext).inflate(R.layout.activity_attraction_list, parent, false);
}
Attraction attraction = mArrayList.get(position);
TextView textView = (TextView) listView.findViewById(R.id.attraction_name);
textView.setText(attraction.getmAttractionName());
ImageView attractionImage = (ImageView) listView.findViewById(R.id.attraction_image);
attractionImage.setImageResource(attraction.getImageResourceId());
try {
InputStream inputStream = getContext().getResources().openRawResource(attraction.getTextFile());
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String eachline;
while ((eachline = br.readLine()) != null) {
TextView attractionDetails = (TextView) listView.findViewById(R.id.attraction_details);
attractionDetails.setText(eachline);
eachline = br.readLine();
// `the words in the file are separated by space`, so to get each words
// eachline = bufferedReader.readLine();
}br.close();
}
catch(IOException ioe){
// TODO Auto-generated catch block
ioe.printStackTrace();
}
TextView attractionName = (TextView) listView.findViewById(R.id.attraction_name);
attractionName.setText(attraction.getmAttractionName());
TextView attractionDetails = (TextView) listView.findViewById(R.id.attraction_details);
attractionDetails.setText(attraction.getTextFile());
return listView;
}
}
listView.xml:
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list">
</ListView>
activity_attraction_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
tools:context=".attractionList">
<ImageView
android:id="#+id/image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_gravity="center_horizontal"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/image"
android:orientation="vertical">
<TextView
android:id="#+id/attraction_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textStyle="bold"
android:textColor="#android:color/black"
/>
<TextView
android:id="#+id/attraction_details"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#android:color/black" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Read more"
android:textAllCaps="false" />
</LinearLayout>
</RelativeLayout>
You try to find listview that is not present in the activity_attraction_list.xml so your listview is null in your case.
Change this
public class attractionList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_list); //Change this line
To
setContentView(R.layout.listview);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am new to android-dev and experiencing the following problem:
All UI-Elements of the View list_excercises_item, which shows a ListView's item, are not referenceable by findViewById() only in the MainActivity-file.
I do already reference UI-Elements of the list_excercises_item in an own ArrayAdapter.
Context:
I want to fill my spinner with some data using an ArrayAdapter.
Exception:
java.lang.NullPointerException
at example.trackfit.MainActivity.onCreate(MainActivity.java:28)
This instruction throws it: spinBodyCategory.setAdapter(arrayAdapter);
spinBodyCategory is null.
list_excercises_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1" android:layout_marginBottom="10px">
<EditText
android:layout_width="0dp"
android:layout_height="fill_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txt_excercise_name"
android:hint="#string/hint_txt_excercise_name"
android:layout_weight="0.4"
android:inputType="text" />
<EditText
android:layout_width="0dp"
android:layout_height="fill_parent"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/txt_input_weight"
android:paddingLeft="5px"
android:layout_weight="0.20"
android:hint="#string/hint_txt_input_weight" />
<Spinner
android:layout_width="0dp"
android:layout_height="fill_parent"
android1:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/spin_body_category"
android:hint="#string/hint_txt_excercise_name"
android:gravity="right"
android:layout_weight="0.40"
android:inputType="text" />
</LinearLayout>
MainActivity.java:
package example.trackfit;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import java.util.ArrayList;
import example.trackfit.Models.Body;
import example.trackfit.Models.Excercise;
public class MainActivity extends AppCompatActivity {
private Spinner spinBodyCategory = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateExcerciseList();
Body[] bodies = Body.values();
ArrayAdapter<Body> arrayAdapter = new ArrayAdapter<Body>(this, R.layout.list_excercises_item, bodies);
ListView listView = (ListView)findViewById(R.id.list_excercises);
spinBodyCategory = (Spinner)findViewById(R.id.spin_body_category);
spinBodyCategory.setAdapter(arrayAdapter);
}
private void populateExcerciseList() {
ArrayList<Excercise> excercises = Excercise.getExcercises();
CustomExcerciseAdapter adapter = new CustomExcerciseAdapter(this, excercises);
ListView listView = (ListView)findViewById(R.id.list_excercises);
listView.setAdapter(adapter);
}
}
CustomExcerciseAdapter.java:
package example.trackfit;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import java.util.ArrayList;
import example.trackfit.Models.Excercise;
public class CustomExcerciseAdapter extends ArrayAdapter<Excercise> {
public CustomExcerciseAdapter(Context context, ArrayList<Excercise> excercises) {
super(context, 0, excercises);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Excercise excercise = getItem(position);
if (convertView == null)
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_excercises_item, parent, false);
EditText txtExcerciseName = (EditText) convertView.findViewById(R.id.txt_excercise_name);
EditText txtInputWeight = (EditText) convertView.findViewById(R.id.txt_input_weight);
txtExcerciseName.setText(excercise.ExcerciseName);
txtInputWeight.setText(Float.toString(excercise.Weight));
return convertView;
}
}
Edit:
This question is not a duplicate, I ofc know what a NullReferenceException is.
I did not know why this exception was thrown, since - I am new to android-dev and didnt know that I can only access childs of the View I set as my contentView.
Because findViewById is called from MainActivity.java, it is trying to find your spinner from the layout you set: activity_main.xml. Which is why you are getting a null pointer exception.
Since you have a spinner for each item on your list, you will have to set it from getView in your custom adapter.
Try copying and pasting
Body[] bodies = Body.values();
ArrayAdapter<Body> arrayAdapter = new ArrayAdapter<Body>(this, R.layout.list_excercises_item, bodies);
spinBodyCategory = (Spinner)convertView.findViewById(R.id.spin_body_category);
spinBodyCategory.setAdapter(arrayAdapter);
to your getView
I am new to android programming and I seem to have come at a stand still for several days now. I am having trouble finding a solution to my problem and tried many different solutions without success. As the title suggests, my code runs successfully but the ListView does not show up on the selected Tabs. Any suggestions of tips would be helpful.
ItemGuide.Java ------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ItemGuide extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), LeatherTab.class, null);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), SilverTab.class, null);
}
}
LeatherTab.java --------------------------------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class LeatherTab extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leather_fragment, container, false); //Fragment Layout inflated
TextView text = (TextView) view.findViewById(R.id.boxtest);//TextView for layout testing
text.setText("Hello");
ListView leather_listview = (ListView) view.findViewById(R.id.leather_list); // List is initialized
leather_listview.setAdapter(new LeatherAdapter(getActivity())); //Custom list adapter passes Context
return view;
}
}
LeatherAdapter.java ------------------------------------------------------
package com.example.alzuni_project;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
class LeatherAdapter extends BaseAdapter {
ArrayList<SingleRow> list;
Context context;
public LeatherAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.leather_list_titles);
String[] descriptions = res.getStringArray(R.array.leather_list_description);
int[] images = {R.drawable.belt, R.drawable.wallet, R.drawable.coincase};
for (int i=0;i<images.length;i++) //Was originally 3
{
new SingleRow(titles[i], descriptions[i], images[i]);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup, false);
TextView title = (TextView) row.findViewById(R.id.leather_title);
TextView description = (TextView) row.findViewById(R.id.leather_description);
ImageView image = (ImageView) row.findViewById(R.id.leather_icon);
SingleRow temp = list.get(position);
title.setText(temp.title);
description.setText(temp.description);
image.setImageResource(temp.image);
return row;//returns the rootView of single_row.xml
}
}
leatherfragment.xml ------------------------------------------------------
<?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"
android:orientation="vertical" >
<TextView
android:id="#+id/boxtest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#CCDDFF" />
<ListView
android:id="#+id/leather_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/boxtest" />
</RelativeLayout>
SingleRow.java -----------------------------------------------------
package com.example.alzuni_project;
class SingleRow {
String title;
String description;
int image;
SingleRow(String title, String description, int image) {
this.title=title;
this.description=description;
this.image=image;
}
}
single_row.xml ---------------------------------------------------
<?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"
android:orientation="vertical" >
<ImageView
android:id="#+id/leather_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="48dp"
android:contentDescription="#string/todo" />
<TextView
android:id="#+id/leather_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#CCCCCC" />
<TextView
android:id="#+id/leather_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/leather_icon"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_below="#+id/leather_title"
android:background="#CCDDFF" />
Your list seems empty , try this in your LeatherAdapter:
list.add(new SingleRow(titles[i],descriptions[i], images[i]));
Inside the for loop .
I'm interested in how you can change the size of the text in the list and then add it to the ListView. I'm using a list_item with custom layout . The question is how you can set the size of the text before it gets into the ListView. I hope for your help.
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android1="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/shop_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="1"
/>
<TextView
android:id="#+id/shop_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="2"
/>
</LinearLayout>
</LinearLayout>
day_list_events.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:id="#+id/layout"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/day_and_data"
android:text="Перелік клієнтів на сьогоднішній день."
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/help_info"
android:text="(Щоб отримати інформацію про клієнта та оформити замовлення - натисніть на відповідного клієнта у списку)"
android:textColor="#A0A0A0"
/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/day_list_event"
>
</ListView>
</LinearLayout>
DayListEventsActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Window;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class DayListEventsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.day_list_events);
sharedPreferences = getSharedPreferences("impInfo", Context.MODE_PRIVATE);
Resources res = this.getResources();
ArrayList<HashMap<String, String>> dayShopsInfo = new ArrayList<HashMap<String, String>>();
String[] shopName = res.getStringArray(R.array.shop_name);
String[] shopAddress = res.getStringArray(R.array.shop_address);
for(int i = 0; i < shopName.length; i++){
HashMap<String, String> dayShopsInfoCont = new HashMap<String, String>();
dayShopsInfoCont.put(KEY_SHOP_NAME, shopName[i]);
dayShopsInfoCont.put(KEY_SHOP_ADDRESS, shopAddress[i]);
System.out.println(i+" "+shopName[i]+" "+shopAddress[i]);
dayShopsInfo.add(dayShopsInfoCont);
}
ListView shopList = (ListView)findViewById(R.id.day_list_event);
SimpleAdapter shopListAdapter = new SimpleAdapter(this,
dayShopsInfo,
R.layout.list_item,
new String[]{KEY_SHOP_NAME, KEY_SHOP_ADDRESS},
new int[]{R.id.shop_name, R.id.shop_address});
shopList.setAdapter(shopListAdapter);
shopList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
private final String KEY_SHOP_NAME = "shop name";
private final String KEY_SHOP_ADDRESS = "shop address";
private SharedPreferences sharedPreferences;
}
UPDATE (Solution).
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class DayListEventsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.day_list_events);
sharedPreferences = getSharedPreferences("impInfo", Context.MODE_PRIVATE);
Resources res = this.getResources();
ArrayList<HashMap<String, String>> dayShopsInfo = new ArrayList<HashMap<String, String>>();
String[] shopName = res.getStringArray(R.array.shop_name);
String[] shopAddress = res.getStringArray(R.array.shop_address);
for(int i = 0; i < shopName.length; i++){
HashMap<String, String> dayShopsInfoCont = new HashMap<String, String>();
dayShopsInfoCont.put(KEY_SHOP_NAME, shopName[i]);
dayShopsInfoCont.put(KEY_SHOP_ADDRESS, shopAddress[i]);
System.out.println(i+" "+shopName[i]+" "+shopAddress[i]);
dayShopsInfo.add(dayShopsInfoCont);
}
ListView shopList = (ListView)findViewById(R.id.day_list_event);
MySimpleAdapter shopListAdapter = new MySimpleAdapter(this,
dayShopsInfo,
R.layout.list_item,
new String[]{KEY_SHOP_NAME, KEY_SHOP_ADDRESS},
new int[]{R.id.shop_name, R.id.shop_address});
shopList.setAdapter(shopListAdapter);
shopList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
public class MySimpleAdapter extends SimpleAdapter{
public MySimpleAdapter(Context context,
List<? extends Map<String, ?>> data,
int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View returnView = super.getView(position, convertView, parent);
TextView shopName = (TextView)returnView.findViewById(R.id.shop_name);
shopName.setTextSize(20.0f);
return returnView;
}
}
private final String KEY_SHOP_NAME = "shop name";
private final String KEY_SHOP_ADDRESS = "shop address";
private SharedPreferences sharedPreferences;
}
Simply do this in the getView() method of the Adapter, to set the font size.
tv.setTextSize(20.0f);
If you are using xml for setting layout for list_item and there you have TextView you can change the size of the text like this:
<TextView
android:id="#+id/text_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20sp" /> // This is a size of your text
There's not "size of text"
You can change the size of the text inside the TextView:
Add:
android:textSize="16sp"
TO your XML
Or you can do it by code in the getView() method in the Adapter:
YOUR_TEXTVIEW.setTextSize(16);
I know this might be a little late, however I noticed that everyone forgot something in their answers. the method setTextSize takes 2 parameters for it's input. The second if a float that is the number of the size you want. The first is a TypedValue Constant to let specify what the number means ie: pixels, dip, sp, etc... so for the setTextSize set to 18sp it would look something like this:
TextView yourTextView = (TextView)findViewById(R.id.yourTextViewId);
yourTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP,18)
and you would do it in the getView of the ArrayAdapter. Hope this helps someone else who was looking for an answer and stumble upon this one.
Try this one
TextView textView = (TextView) findViewById (R.id.yourTextViewId);
textView.setTextSize(18);