I'm making an app that deals with a fragment and I keep getting an undefined error for a constructor.
`
public class ClientFragment extends Fragment {
private static final ClientFragment This = null;
final ClientFragment context = This;
private static String TAG = "This thing here";
private static final String DIALOG_IMAGE = "image";
private static final int REQUEST_PHOTO = 1;
static final String EXTRA_MEM_ID = "com.example.project2.memID";
private Scrap mScraps;
Uri imageFileUri;
public static ClientFragment newInstance(UUID memID) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_MEM_ID, memID);
ClientFragment fragment = new ClientFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this snags the UUID sent from MainActivity and tosses it to BookMarks
UUID memId = (UUID)getArguments().getSerializable(EXTRA_MEM_ID);
mScraps = BookMarks.get(getActivity()).getScraps(memId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_scraps, parent, false);
final ListView mListView= (ListView)v.findViewById(R.id.listview);
ScrapAdapter adapter = new ScrapAdapter(mScraps);
mListView.setAdapter(adapter); //setListAdapter sets the adapter to a specific listview
return v;
}
private static final int TAKE_PICTURE_REQUEST = 0;
private class ScrapAdapter extends ArrayAdapter<Scrap> {
public ScrapAdapter(ArrayList<Scrap> scraps) {
super(getActivity(), 0, scraps);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_memory, null);
}
// Configure the view
Scrap c = getItem(position);
//shows title
TextView titleTextView =(TextView)convertView.findViewById(R.id.list_item_titleTextView);
titleTextView.setText(c.getTitle());
//shows date memory was made
TextView dateTextView =(TextView)convertView.findViewById(R.id.list_item_dateTextView);
dateTextView.setText(c.getDate().toString());
return convertView;
}
}}`
The error is coming from ScrapAdapter adapter = new ScrapAdapter(mScraps); specifically the new ScrapAdapter(mScraps);
The error I receive is "The constructor ClientFragment.ScrapAdapter(Scrap) is undefined"
your constructor accepts an ArrayList<Scrap> as argument
public ScrapAdapter(ArrayList<Scrap> scraps)
but you are passing an Scrap object to it instead
ScrapAdapter adapter = new ScrapAdapter(mScraps);
Either pass ArrayList of Scrap to ScrapAdapter :
ArrayList<Scrap> mScraps;
ScrapAdapter adapter = new ScrapAdapter(mScraps);
Or change ScrapAdapter constructor parameter ArrayList to Scrap :
public ScrapAdapter(Scrap scraps) {
super(getActivity(), 0, scraps);
}
Your constructor need an ArrayList :
public ScrapAdapter(ArrayList<Scrap> scraps)
But you are passing an Object, not the ArrayList of Object :
private Scrap mScraps;
ScrapAdapter adapter = new ScrapAdapter(mScraps);
Maybe what you need to do is creating an ArrayList of Scrap and pass it. Or maybe, you want to change your constructor's parameter to receive a Scrap instead of ArrayList.
Related
I am passing value as string from an activity through intent to this Page Activity and adding it to an arraylist and setting that list to an list view using base adapter.But unfortunately its the values are not showing in listview.
And I am not able to figure out how to set that value to the textview present in PagesAdapter.java.
Please help me guys.
Pages.java
public class Pages extends Activity implements AdapterView.OnItemClickListener {
private static final String TAG = null;
private List<String> list = new ArrayList<>();
private ListView listView;
private PagesAdapter pageadapter;
private String androidOS;
private String device_uuid;
private String contributor_id;
public String tocName;
public String categoryName;
private SessionManager session;
private String first_Page;
private String last_Page;
private String current_Page;
private String firstPage;
private String lastPage;
private String currentPage;
ProgressDialog loading;
private String page;
private String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
page = getIntent().getExtras().getString("CONTENT");
name = getIntent().getExtras().getString("NAME");
session = new SessionManager(getApplicationContext());
SharedPreferences pref = this.getSharedPreferences("preferences", 0);
firstPage = pref.getString("firstpage",null);
lastPage = pref.getString("lastpage",null);
currentPage = pref.getString("currentpage",null);
contributor_id = pref.getString("contributor_id",null);
loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//getData();
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
androidOS = Build.VERSION.RELEASE;
device_uuid = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
list.add(name);
pageadapter = new PagesAdapter(Pages.this, list);
listView.setAdapter(pageadapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(Pages.this, RecordComposition.class);
i.putExtra("PAGE",page);
startActivity(i);
}
}
PagesAdapter.java
public class PagesAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<String> Pagelist;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public PagesAdapter(Activity activity, List<String> billionairesItems) {
this.activity = activity;
this.Pagelist = billionairesItems;
}
#Override
public int getCount() {
return Pagelist.size();
}
#Override
public Object getItem(int location) {
return Pagelist.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.pages_view, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView name = (TextView) convertView.findViewById(R.id.name);
// String m = Pagelist.get(position);
// thumbNail.setImageUrl(m.getImage(), imageLoader);
// name.setText(m.get);
return convertView;
}
}
You have to set value to the textView :
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(Pagelist.get(position));
The first problem is related to your list variable. You are passing it as a Empty List, because you are not populating it with String values.
The adapter will scan your list and verify that there is no data to display, so try to put some data inside the list variable and test the ListView again.
The second question is easy to resolve, just add these lines inside your getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(Pagelist.get(position));
}
I am working on an Android app, in which the user uploads a photo. Now, I am calling a method from the server, which will return me a list of users. I would like to display this list along with the photos.
The images stored in the server are in byte-array. So I am converting them to String and then to Bitmap for showing. Unfortunately, it is not working as I am doing stuff with a Adapters as well. The image retrieved in adapter class is null. What am I doing wrong?
OtherUsers.java :
public class OtherUsers extends Activity {
private PersonServiceImpl personService = new PersonServiceImpl();
private static volatile List<RestPerson> restPersonList = new ArrayList<>();
public static final String firstName = "firstname";
public static final String userImage = "userimage";
static final Long userId = (long)0;
ListView listView;
UserAdapter userAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.displayuserlist);
restPersonList = this.personService.getOtherUsers();
// Base64 base64Encoder = new Base64();
ArrayList<HashMap<String, String>> usersArrayHashList = new ArrayList<>();
for(RestPerson restPerson : restPersonList){
HashMap<String, String> restDisplay = new HashMap<>();
restDisplay.put("userId",String.valueOf(restPerson.getUserId()));
restDisplay.put("firstName",restPerson.getFirstName());
restDisplay.put("userImage","data:image/png;base64," + Base64.encode(restPerson.getProfilePhoto()));
usersArrayHashList.add(restDisplay);
}
listView = (ListView) findViewById(R.id.usersdisplaylist);
userAdapter = new UserAdapter(this,usersArrayHashList);
listView.setAdapter(userAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Long userid = restPersonList.get(position).getUserId();
Log.d("Userid is ", String.valueOf(userid));
}
});
UserAdapter class :
public class UserAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public UserAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.userprofiles, null);
TextView username = (TextView) view.findViewById(R.id.userName);
ImageView userImage = (ImageView) view.findViewById(R.id.userImage);
HashMap<String, String> usersList = new HashMap<>();
usersList = data.get(position);
username.setText(usersList.get(OtherUsers.firstName));
String image = usersList.get(OtherUsers.userImage);
Log.d("Image is ",image);
byte[] newImageBytes = image.getBytes();
Bitmap bitmap = BitmapFactory.decodeByteArray(newImageBytes,0,newImageBytes.length);
userImage.setImageBitmap(bitmap);
userImage.setImageBitmap(null);
return view;
}
}
If there is any other information required, kindly let me know. Thanks.
Update
Sorry, forgot to put LogCat
08-24 13:43:16.618 29948-29948/internetlegion.com.gradlecheck E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: internetlegion.com.gradlecheck, PID: 29948
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at internetlegion.com.gradlecheck.Adapters.UserAdapter.getView(UserAdapter.java:62)
at android.widget.AbsListView.obtainView(AbsListView.java:2347)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1270)
at android.widget.ListView.onMeasure(ListView.java:1182)
at android.view.View.measure(View.java:17547)
data struct that you have used in adapter is very strange. it's better to create one class with three property and send one list of those to adapter class.
any way, your problem is :
public static final String userImage = "userimage";
you define userImage with value userimage, then you insert into hashmap with "userImage" that is not equal with value of userImage ( value have lower case i) then you have try to get "userimage" from hashmap that is not exists, so value is null.
Answer:
you can change following line:
restDisplay.put("userImage","data:image/png;base64," + Base64.encode(restPerson.getProfilePhoto()));
to
restDisplay.put(userImage,"data:image/png;base64," + Base64.encode(restPerson.getProfilePhoto()));
but better way is create custom object.
I used fragment in my app and i'm using SQLite to save local data. But when I finished saving data, and I swipe the page, my listView is not refreshed with new data (Only showing old data). I have tried to provide a method notifyDataSetChanged() on my adapter, but it's not working.
My Base Adapter class :
public class LocalDataAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<LocalDataBean> data;
private static LayoutInflater inflater = null;
public LocalDataAdapter(Activity a, ArrayList<LocalDataBean> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void setItem(ArrayList<LocalDataBean> data){
this.data = data;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = inflater.inflate(R.layout.list_item, null);
TextView nama_konsumen = (TextView) v.findViewById(R.id.nama_konsumen);
TextView no_telp = (TextView) v.findViewById(R.id.no_telp);
TextView no_hp_cdma = (TextView) v.findViewById(R.id.no_hp_cdma);
TextView no_hp_gsm = (TextView) v.findViewById(R.id.no_hp_gsm);
LocalDataBean obj = (LocalDataBean) getItem(position);
nama_konsumen.setText(obj.getNamaKonsumen());
no_telp.setText(obj.getNoTelp());
no_hp_cdma.setText(obj.getNoCMDA());
no_hp_gsm.setText(obj.getNoGSM());
return v;
}
}
My fragment class :
public class LocalDataFragment extends Fragment {
View view;
Activity act;
SQLHandlerBean utilSql;
ArrayList<LocalDataBean> localdatabean = new ArrayList<LocalDataBean>();
LocalDataAdapter adapter;
ListView list;
public static final String TAG = LocalDataFragment.class.getSimpleName();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.layout_local_data, null);
act = getActivity();
list = (ListView) view.findViewById(R.id.listViewLocalData);
utilSql = new SQLHandlerBean(this.act);
adapter = new LocalDataAdapter(act, localdatabean);
localdatabean = new ArrayList<LocalDataBean>();
list.setAdapter(adapter);
if (utilSql.ReadAllLocalData().size() < 1) {
Toast.makeText(act, "DATA EMPTY!", Toast.LENGTH_LONG).show();
} else {
localdatabean = utilSql.ReadAllLocalData();
Log.e(TAG, "TOTAL DATA : "+localdatabean.size());
adapter.setItem(localdatabean);
adapter.notifyDataSetChanged();
}
return view;
}
}
Is adapter.notifyDataSetChanged() placement correct?
No, the placement is not in the right place.
As you have placed the notifyDataSetChanged() inside of the onCreateView() method. It will be only invoked 1st time the fragment is launched.
Rather you can add a refresh button in your layout (or in you action bar). And along with the insertion/deletion method of the data, place the notifyDataSetChanged() at the bottom of the click event of that button.
By doing this user can refresh the page whenever they want.
And if you want to refresh the page by swipping the view then, SwipeRefreshLaoyout could be a perfect alternative.
You can check this blog.
Right now I use setAdapter to update my ListView, but I think the proper way is to use notifiyDatasetChanged() and I can't get that to work in my main class (it's in the adapter). Here is the error:
The method notifyDatasetChanged() is undefined for the type ListAdapter
I'm guessing there is a better way of doing this - can anyone point me in the right direction?
Here's the relevant parts of my code:
public class ScoreList extends SherlockFragmentActivity {
private ListView listViewScore;
static List<Score> listScore = new ArrayList<Score>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_list);
ctx = this;
listScore = dbh.getAllScores();
listViewScore = (ListView) findViewById(R.id.score_list);
listViewScore.setAdapter(new ScoreListAdapter(ctx,
R.layout.score_row_item, listScore));
listViewScore.getAdapter().notifyDatasetChanged(); //this is where I get the error
}
}
Here's the adapter:
public class ScoreListAdapter extends ArrayAdapter<Score> {
private int resource;
private LayoutInflater inflater;
public ScoreListAdapter(Context ctx, int resourceId, List<Score> objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(ctx);
//context = ctx;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = (LinearLayout) inflater.inflate(resource, null);
Score score = getItem(position);
TextView txtName = (TextView) convertView.findViewById(R.id.name);
txtName.setText(score.getName());
TextView txtScoreChange = (TextView) convertView
.findViewById(R.id.scoreChange);
int scoreChange = Integer.parseInt(score.getScoreChange());
if (scoreChange > 0)
txtScoreChange.setText("+" + scoreChange);
else if (scoreChange < 0)
txtScoreChange.setText("" + scoreChange);
else
txtScoreChange.setText("");
TextView txtScoreTotal = (TextView) convertView
.findViewById(R.id.scoreTotal);
txtScoreTotal.setText(score.getScoreTotal());
final LinearLayout currentRow = (LinearLayout) convertView
.findViewById(R.id.scoreRowLayout);
notifyDataSetChanged();
return convertView;
}
}
Create an instance of your custom adapter, so you can use it anywhere you like...
public class ScoreList extends SherlockFragmentActivity {
private ListView listViewScore;
private ScoreListAdapter adapter;
static List<Score> listScore = new ArrayList<Score>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_list);
ctx = this;
listScore = dbh.getAllScores();
listViewScore = (ListView) findViewById(R.id.score_list);
adapter = new ScoreListAdapter(ctx, R.layout.score_row_item, listScore);
listViewScore.setAdapter(adapter);
adapter.notifyDatasetChanged();
}
}
By the way, if your listScore array is already loaded, then you do not need to use
adapter.notifyDatasetChanged();
Dont call the notifyDataSetChanged(); method while creation.
only call it when content of your listViewScore changes.. and to use it at that time-
replace
listView.getAdapter().notifyDatasetChanged();
with
((ScoreListAdapter)listView.getAdapter()).notifyDataSetChanged();
and see the magic...
thanks.
I'm trying to populate a ListView with an ArrayList> using a base adapter. The ArrayList is populated by a database, and it is possible for the database to have no entries, and thus a empty ArrayList, for example when the app is launched for the first time. While the ArrayList is empty, I receive a non de-script "java.lang.RuntimeException: Unable to start activity ComponentInfo ... java.lang.NullPointerException".
My onCreate method looks like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.samples_list_layout);
mContext = getApplicationContext();
lv = getListView();
list = myDatabase.getInstance(mContext).getAllSamples();
sa = new SamplesAdapter(this, list);
lv.setAdapter(sa);
registerForContextMenu(lv);
}
Setting lv.setAdapter(null) will get the app to display the empty list view I have set up. However, when I leave it up to the BaseAdapter, I get the error.
I've followed the 2 Android List8.java and List14.java examples, and either way give the same results.
My BaseAdapter class looks like this:
public class SamplesAdapter extends BaseAdapter {
private static final String SAMPLE_NAME_COL = "name";
private static final String SAMPLE_HOST_COL = "host";
private static final String SAMPLE_ICON_COL = "icon";
private static final String SAMPLE_MODIFIED_STAMP_COL = "moddate";
private Context mContext;
private ArrayList<HashMap<String, String>> samples = new ArrayList<HashMap<String, String>>();
public SamplesAdapter(Context c, ArrayList<HashMap<String, String>> list){
mContext = c;
samples = list;
}
public int getCount() {
return samples.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.samples_row_layout, parent, false);
TextView name = (TextView) v.findViewById(R.id.samples_name);
name.setText(samples.get(position).get(SAMPLE_NAME_COL));
TextView host = (TextView) v.findViewById(R.id.samples_host);
host.setText(samples.get(position).get(SAMPLE_HOST_COL));
TextView moddate = (TextView) v.findViewById(R.id.samples_mod_stamp);
moddate.setText(samples.get(position).get(SAMPLE_MODIFIED_STAMP_COL));
return v;
}
}
I should also note that the ListView properly displays items when there is something to show. It only fails when the ArrayList is empty. Also, I'm using Android 2.2 (Not the greatest, I know). Any help would be greatly appreciated.
let getCount return 0, in orded to avoid the NPE:
public int getCount() {
return (samples == null) ? 0 : samples.size();
}