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);
Related
I am trying to display some recipe data after you search the recipe in the search bar and click the search button inside the search fragment. I am using recycler view inside the search fragment to display the data below the search bar and the button.
Here is the code for the fragment_search.xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.SearchFragment">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="-230dp"
android:src="#drawable/home_oval" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FOODIES"
android:textSize="40dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<SearchView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:queryHint="Find your today's recipe"
android:iconifiedByDefault="false"
android:background="#drawable/searchoval"
android:id="#+id/searchbar"
/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="search"
android:background="#drawable/rounded_btn"
android:layout_below="#+id/searchbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/button1"/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:src="#drawable/ic_man_searching_location_using_gps_2127154_0"
android:layout_below="#+id/button1"
android:id="#+id/searching_logo"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searching_text"
android:text="Search for yummy delicacies today"
android:layout_centerHorizontal="true"
android:textAlignment="center"
android:fontFamily="#font/quicksand"
android:layout_below="#+id/searching_logo"
android:textSize="25dp"
android:textColor="#color/black"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button1"
android:id="#+id/recycler_view"
>
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</FrameLayout>
Here is my SearchFragment.java file.
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "http://localhost:5000/" + query;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonArrayRequest);
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I am fething the api and setting the arraylists and adapter inside the onClick listener
but I keep getting the "E/RecyclerView: No adapter attached; skipping layout" Error in the logcat.
Here is the code for the adapter.
package com.example.recipeappandroid.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import com.example.recipeappandroid.Viewholder.recipeViewHolder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecipeAdapter extends RecyclerView.Adapter<recipeViewHolder>{
private Context mContext;
private ArrayList<Recipe> mRecipe;
public RecipeAdapter(Context context,ArrayList<Recipe> recipe) {
mContext = context;
mRecipe = recipe;
}
public void setData(ArrayList<Recipe> mRecipe) {
this.mRecipe = mRecipe;
}
#NonNull
#Override
public recipeViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_row, viewGroup, false);
return new recipeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull recipeViewHolder viewHolder, int i) {
Recipe recipe = mRecipe.get(i);
Picasso.get().load(recipe.getImg()).into(viewHolder.image);
viewHolder.recipe_title.setText(recipe.getTitle());
viewHolder.recipe_data.setText(recipe.getData());
}
#Override
public int getItemCount() {
return mRecipe.size();
}
}
Here is my solution
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//change code:
recipeList = new ArrayList<>();
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
recyclerView.setAdapter(recipeAdapter);
//after get data in API:
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
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;
}
}
When I scroll past an item and come back to it, it changes it's position until I click on it, then it will correctly align itself. How can I solve this. Sorry I am still at the start of the project so my code is a bit messy.
This is my code:
package com.example.r_corp.androidslauncher;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
PackageManager packageManager;
Intent mainIntent = null;
static ArrayList<app> appList;
static GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_all_apps_layout);
gridView = (GridView)findViewById(R.id.GridView);
gridView.setNumColumns(4);
packageManager = getPackageManager();
mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
appList = getApps();
show();
}
public ArrayList<app> getApps(){
List<ResolveInfo>apps = packageManager.queryIntentActivities(mainIntent, 0);
ArrayList<app> Apps = new ArrayList();
for(ResolveInfo ri : apps){
app App = new app();
App.icon = ri.loadIcon(packageManager);
App.Name = ri.loadLabel(packageManager).toString();
Apps.add(App);
}
return Apps;
}
public void show(){
ArrayAdapter<app> adapter = new ArrayAdapter<app>(this, R.layout.item,
appList) {
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.item,null);
}
ImageView appIcon = (ImageView) convertView
.findViewById(R.id.imageView);
appList.get(position).icon.setBounds(10,10,10,10);
appIcon.setImageDrawable(appList.get(position).icon);
appIcon.setLayoutParams(new RelativeLayout.LayoutParams(85, 85));
appIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
appIcon.setPadding(8, 8, 8, 8);
TextView appName = (TextView) convertView
.findViewById(R.id.textView);
appName.setText(appList.get(position).Name);
return convertView;
}
};
gridView.setFocusable(true);
gridView.setAdapter(adapter);
}
}
class app{
Drawable icon;
String Name;
}
show_all_apps_layout:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:stretchMode="columnWidth"
android:focusableInTouchMode="true"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:id="#+id/GridView"/>
item:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:text="TextView" />
</RelativeLayout>
Thanks in advance for your helpfulness.
I have a listView where a user can enter input to change the textView on each listView row. When you scroll the row off the screen the edited text goes away and the default text reappears. I know this is fixed with the viewHolder but I can't get it to work in my custom adapter class.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import java.util.ArrayList;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> Chores = new ArrayList<>();
//Chores.add("");
final ListAdapter MyAdapter = new CustomAdapter(this, Chores);
ListView listViewObject = (ListView)findViewById(R.id.customListView_ID);
listViewObject.setAdapter(MyAdapter);
listViewObject.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String ChoreString = String.valueOf(parent.getItemAtPosition(position));
}
}
);
final Button button = (Button) findViewById(R.id.button_ID);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Chores.add("");
((ArrayAdapter)MyAdapter).notifyDataSetChanged();
}
});
}
}
CustomAdapter.java
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import static com.example.emilythacker.chorelist.R.id.textView_ID;
class CustomAdapter extends ArrayAdapter{
ArrayList<String> choreText;
public CustomAdapter(Context context, ArrayList choreText) {
super(context, R.layout.custon_listview_row, choreText);
this.choreText = choreText;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
//final TextView textView = (TextView) customView.findViewById(textView_ID);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(R.layout.custon_listview_row, null);
holder = new ViewHolder();
holder.imageButton = (ImageButton) convertView.findViewById(R.id.imageButton_ID);
holder.textView = (TextView) convertView.findViewById(textView_ID);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(choreText.get(position));
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//what happens when textView is clicked
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
final EditText input = new EditText(getContext());
input.setHint("hint");
alertDialog.setView(input);
alertDialog.setTitle("Set Chore");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
holder.textView.setText(input.getText().toString());
dialog.dismiss();
}
});
alertDialog.show();
}
});
holder.imageButton.setImageResource(R.drawable.clock);
return convertView;
}
static class ViewHolder {
ImageButton imageButton;
TextView textView;
}
}
activity_main.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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.emilythacker.chorelist.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/customListView_ID"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp" />
<Button
android:text="Add Chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/button_ID" />
</RelativeLayout>
custon_listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="60dp">
<ImageButton
android:layout_width="60dp"
android:scaleType="fitCenter"
app:srcCompat="#drawable/clock"
android:id="#+id/imageButton_ID"
android:layout_height="60dp"
android:background="#null"
android:layout_alignParentRight="true"
android:padding="5dp"
android:layout_weight="1" />
<TextView
android:text="Click here to add chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/textView_ID"
android:textSize="25dp"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/imageButton_ID"
android:layout_marginEnd="11dp"
/>
</RelativeLayout>
When text is entered into the edit text, you need to save it to a variable associated with that position, and in getView you need to set the text of the editText to that position's value. Otherwise you'll just have whatever random value was in there last.
Basically, any value that can change in a row's UI must be saved and written to it in getView.
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