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
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);
Following my previous post where I asked about implementing parceable objects, the solution I got was to use setRetainInstance(true); method.
#CommonsWare provided me a sample which I modified as follows:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="387dp"
android:layout_height="103dp"
android:text="New Text"
android:id="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
RotationFragmentDemo.java
package com.rotationfragment;
import android.app.Activity;
import android.os.Bundle;
public class RotationFragmentDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This check returns 'null' for the first time when there are no fragments
if (getFragmentManager().findFragmentById(android.R.id.content) == null) {
getFragmentManager().beginTransaction().add(android.R.id.content, new RotationFragment()).commit();
}
}
}
RotationFragment.java
package com.rotationfragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class RotationFragment extends Fragment implements
View.OnClickListener {
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
// This should help to retain fragment
setRetainInstance(true);
View result=inflater.inflate(R.layout.activity_main, parent, false);
result.findViewById(R.id.button).setOnClickListener(this);
textView = (TextView)result.findViewById(R.id.textView);
return(result);
}
#Override
public void onClick(View v) {
textView.setText("Hello.");
}
}
Upon rotation the text in TextView is not restored.
I know some of you would suggest using parceable writeString parceable method to fix this simple example but I want to know why is the Fragment not retained here using setRetainInstance(true)?
And I don't need to retain a string but Socket, Thread and Activity as in previous post.
See the answer, "onRetainInstance saves the Fragment object, but I still have to rebuild UI in onCreateView", So you have to restore the state of your views manually
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
I'm using slidemenu in my project.
In my fragment i have a listview that reads some data from db.
My fragment:
package ir.monocode.azmooneEstekhdami;
import ir.monocode.azmoonEstekhdami.R;
import java.util.ArrayList;
import android.app.Fragment;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class QuestionsFragment extends Fragment {
public QuestionsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_questions, container, false);
/******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
// setListData();
// CustomListViewValuesArr.clear();
MySQLiteHelper db = new MySQLiteHelper(getActivity());
ArrayList<CatsModel> CustomListViewValuesArr = db.getAllCelebs();
Resources res = getResources();
// now you must initialize your list view
ListView listview = (ListView) view.findViewById(R.id.listView1);
//listview.setFastScrollEnabled(true);
/**************** Create Custom Adapter *********/
CustomAdapter adapter = new CustomAdapter(getActivity(),CustomListViewValuesArr, res);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// do things with the clicked item
Toast.makeText(getActivity(), ""+ position, Toast.LENGTH_LONG).show();
}
});
return view;
}
}
My fragment layout is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dedede"
android:orientation="vertical" >
<ImageView
android:id="#+id/cimageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/top"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp" >
</ListView>
</LinearLayout>
But when i want to use onitemclicklistener it doesn`t work. Where is my problem?
As you can see i use customapater and
public void onItemClick(int mPosition) {
// TODO Auto-generated method stub
}
in my main activity.
You need to add these properties for your custom list item row layout widgets which is already inflated in getView() method by you.
android:focusable="false"
android:focusableInTouchMode="false"