[EDIT] I'm new to android development, so please bear with me. I have two java classes named Join Game, extends to AppCompatActivity and HintList,extends to ArrayAdapter<>. This is connected to a database. So maybe its one of the factors?
For the layout of join game, I have a listview
and for the layout of hintlist I have three textview.
The code goes this way
JoinGame
public class JoinGame extends AppCompatActivity {
ListView list;
String[] itemdescription = {};
String[] itemhints = {};
String[] itemlocasyon = {};
ProgressDialog progress;
View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joingame);
Button schan = (Button)findViewById(R.id.tarascan);
schan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(JoinGame.this,ScanActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
progress = new ProgressDialog(this);
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
RequestFactory.joingameitems(JoinGame.this, RequestFactory.user_id, new RequestCallback<JSONArray>() {
#Override
public void onSuccess(final JSONArray response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
} catch (JSONException e) {
e.printStackTrace();
}
} ////////// below this is the adapter
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
}
});
}
#Override
public void onFailed(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(JoinGame.this, message, Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
HintList
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, null, true);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
}
I actually retrieved the data (here)
E/DB: [{"description":"chinese garter","location":"near Tricycle station","hint":"garter plus chinese"},{"description":"isang pinoy game","location":"near ....","hint":"may salitang baka"},{"description":"\"tinik\"","location":"below...","hint":"may salitang tinik"},{"description":"aka Tinubigan","location":"at the back...","hint":"katunog ng pintero"},{"description":"\"knock down the can\"","location":"near...","hint":"gumagamit ng lata"}]
but it doesnt display on my listview
I dont know anymore what I should do.
I actually tried making this (I added view)
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)view.findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
but it will only returns an error of java.lang.NullPointerException: Attempt to invoke virtual method
Change this:
View rowView = inflater.inflate(R.layout.hints_list, null, true);
to:
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
Modify your getView() method to:
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
try adding getCount
#Override
public int getCount() {
return itemHints.length;
}
Try to change your code to this
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
private LayoutInflater inflater=null;
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return itemHints.length;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
view=inflater.inflate(R.layout.hints_list, null, true);
holder = new ViewHolder(view);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
holder.itemDesc2.setText(itemDesc[position]);
holder.itemHint.setText(itemHints[position]);
holder.itemLocation2.setText(itemLocation[position]);
return view;
}
static class ViewHolder{
TextView itemDesc2,itemHint,itemLocation2;
ViewHolder(View view) {
itemDesc2 = (TextView)view.findViewById(R.id.itemdescription);
itemHint = (TextView)view.findViewById(R.id.itemhint);
itemLocation2 = (TextView)view.findViewById(R.id.itemlocation);
}
}
}
My suggestions is create a bean class (DetailsBean), used for setter and getter method, and also the ArrayList (details1).
List<DetailsBean> details1 = new ArrayList<>(); // declare this as global
Then add the bean to below code
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
// here the bean
DetailsBean dbean = new DetailsBean(itemDescription, itemhints, itemlocasyon);
details1.add(dbean); // add all the data to details1 ArrayList
HintList hladapt = new HintList(getActivity(), details1);
(ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
} catch (JSONException e) {
e.printStackTrace();
}
}
Your DetailsBean should looked like this
public class DetailsBean {
private String itemDescription="";
private String itemhints="";
private String itemlocasyon ="";
public DetailsBean(String description, String hints, String itemlocasyon) {
this.itemDescription=description;
.....
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDesription;
}
public String getItemDescription() {
return itemDescription;
}
....
}
Then your HintList
public class HintList extends BaseAdapter{
Activity context;
List<DetailsBean> details;
private LayoutInflater mInflater;
public CustomBaseAdapter(Activity context,List<DetailsBean> details) {
this.context = context;
this.details = details;
}
........
}
Add these Override methods in your adapter
#Override
public int getCount() {
return itemHints.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
Related
Am looking to create a fragment conaining listview by retriveing data from firebase database.This listview gets cards having buttons and seekbar. All I want is to have a global variable listen to these buttons. I tried creating onClicklistener in the fragment itself but wasn't successful.Then I created onClicklistener for these buttons on the Adapter itself which was working. Now when I use the buttonclick to create a Toast, the Toast string is coming up as I expect. But the problem is that I want this Toasted string to store somewhere like global variable so that I could use it in another fragment as well. So I used:
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication)getContext()).setCartitem("XYZ");
inside my adapter class's on Click Listener itself but the application crashes showing error log "First cannot be cast to com.fastfrooot.fastfrooot.MyApplication". First being my Activity containing Fragment and MyApplication is the class extending application.
MyApplication.java
package com.fastfrooot.fastfrooot;
import android.app.Application;
import android.widget.Button;
public class MyApplication extends Application {
private boolean[] cartsitem = {
false,
false,
false,
false,
false,
false
};
private String orderitem;
private String pkname;
private boolean oncomp = false;
private Button[] cartbuttons = new Button[20];
private String cartitem = "Alpha";
public boolean[] getcartsitem() {
return cartsitem;
}
public void setcartsitem(boolean[] cartsitem) {
this.cartsitem = cartsitem;
}
public String getorderitem() {
return orderitem;
}
public void setorderitem(String orderitem) {
this.orderitem = orderitem;
}
public String getpkname() {
return pkname;
}
public void setpkname(String pkname) {
this.pkname = pkname;
}
public boolean getoncomp() {
return oncomp;
}
public void setoncomp(boolean oncomp) {
this.oncomp = oncomp;
}
public Button[] getcartbuttons() {
return cartbuttons;
}
public void setCartbuttons(Button[] cartbuttons) {
this.cartbuttons = cartbuttons;
}
public String getCartitem() {
return cartitem;
}
public void setCartitem(String cartitem) {
this.cartitem = cartitem;
}
}
public class CustomListAdapterfir extends ArrayAdapter < Cardfir > {
private static final String TAG = "CustomListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
private int procount;
String Cartkeitem;
private static class ViewHolder {
TextView title;
ImageView image;
TextView Status;
Button cartbutton;
SeekBar seekbar;
}
public CustomListAdapterfir(Context context, int resource, List < Cardfir > objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
//sets up the image loader library
setupImageLoader();
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the persons information
final String title = getItem(position).getTitle();
String imgUrl = getItem(position).getImgURL();
final String Status = getItem(position).getStatus();
Button cartbutton = getItem(position).getCartbutton();
final SeekBar seekBar = getItem(position).getSeekbar();
try {
//create the view result for showing the animation
final View result;
//ViewHolder object
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.cardTitle);
holder.Status = (TextView) convertView.findViewById(R.id.cardstat);
holder.image = (ImageView) convertView.findViewById(R.id.cardImage);
holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBarf);
holder.cartbutton = (Button) convertView.findViewById(R.id.Addbutton);
result = convertView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
holder.title.setText(title);
holder.Status.setText(Status);
holder.cartbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int seekerpos = holder.seekbar.getProgress() + 1;
Cartkeitem = title + " " + String.valueOf(seekerpos);
Toast.makeText(mContext, Cartkeitem, Toast.LENGTH_SHORT).show();
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication) getContext()).setCartitem("XYZ");
}
});
holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//create the imageloader object
ImageLoader imageLoader = ImageLoader.getInstance();
int defaultImage = mContext.getResources().getIdentifier("#drawable/logo", null, mContext.getPackageName());
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();
imageLoader.displayImage(imgUrl, holder.image, options);
return convertView;
} catch (IllegalArgumentException e) {
Log.e(TAG, "getView: IllegalArgumentException: " + e.getMessage());
return convertView;
}
}
private void setupImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
}
}
public class Tab1fragment extends Fragment implements View.OnClickListener {
private static final String TAG = "TAG1 fragment";
private ListView mListView;
DatabaseReference Complete = FirebaseDatabase.getInstance().getReference();
DatabaseReference Products = Complete.child("Products");
ValueEventListener productlistener;
final ArrayList < Cardfir > list = new ArrayList < Cardfir > ();
String productname;
String producttype;
final ArrayList < Button > Cartbuttons = new ArrayList < Button > ();
final ArrayList < SeekBar > Seekbars = new ArrayList < SeekBar > ();
int productnumber = -1;
Button[] Cartsbut = new Button[20];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listview);
productlistener = Products.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot delphi: dataSnapshot.getChildren()) {
productnumber = productnumber + 1;
productname = delphi.child("Name").getValue().toString();
producttype = delphi.child("Type").getValue().toString();
list.add(new Cardfir("drawable://" + R.drawable.trans, productname, producttype));
}
CustomListAdapterfir adapter = new CustomListAdapterfir(getActivity(), R.layout.card_layout_liveorder, list);
mListView.setAdapter(adapter);
Products.removeEventListener(productlistener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "HI", Toast.LENGTH_SHORT).show();
}
}
I have a gridview which should show emojies that are retrieved from the server as urls, I was able to retrieve the urls and put it inside an arraylist, however using the gridview adapter, no images show at all, I've tried debugging by handcoding the url outside the for loop and it showed the image, which means that nothing is wrong with my adapter, also when I try to hardcode the url inside the for loop like arraylist.add("the url") no image appears, here's my code, please advise why the images are not showing, appreciate your assistance
BottomSheetDialog_Smiles.java
Communicator.getInstance().on("subscribe start", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONDictionary response = (JSONDictionary) args[0];
String str = response.get("emojiPack").toString();
JSONArray emojies = new JSONArray(str);
for (int i = 0; i < emojies.length(); i++) {
JSONObject response2 = (JSONObject)
emojies.getJSONObject(i);
emojiModel = new EmojiModel((String)
response2.get("urlFile"));
emojiUrl = emojiModel.getEmojiFile();
JSONDictionary t =
JSONDictionary.fromString(response2.toString());
emojiModel.init(t);
emojieModels.add(emojiModel);
}
ImageAdapter2 emojiAdapter = new
ImageAdapter2(getApplicationContext(), emojieModels);
gridView2.setAdapter(emojiAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
ImageAdapter2.java
public class ImageAdapter2 extends BaseAdapter {
private Context context;
private ArrayList<String> emojieImages = new ArrayList<String>();
// Constructor
public ImageAdapter2(Context context, ArrayList<String>
emojieImagesList) {
this.context = context;
this.emojieImages = emojieImagesList;
}
#Override
public int getCount() {
return emojieImages.size();
}
#Override
public Object getItem(int position) {
return emojieImages.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
ImageView imageView;
}
#Override
public View getView(final int position, View convertView, ViewGroup
parent) {
Holder holder = new Holder();
LayoutInflater inflater = (LayoutInflater)
getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.smiles_items_layout, null);
holder.imageView = (ImageView)
grid.findViewById(R.id.smile_image_view);
Picasso.with(getApplicationContext())
.load(emojieImages.get(position))
.fit()
.centerInside()
.into(holder.imageView);
return grid;
}
}
EmojiModel.java
public class EmojiModel {
private int id;
private int price;
public String urlFile;
public EmojiModel(String urlFile) {
this.id=id;
this.price=price;
this.urlFile=urlFile;
}
public String getEmojiFile() {
return urlFile;
}
public void init(JSONDictionary data){
try{
urlFile = (String) data.get("urlFile");
id = Integer.parseInt((String) data.get("id"));
price = Integer.parseInt((String) data.get("price"));
}catch(Exception e){
e.printStackTrace();
}
}
}
Try this
Picasso.with(this)
.load(imageUrl)
.fit()
.centerInside()
.into(imageViewFromUrl, new Callback() {
#Override
public void onSuccess() {
Log.i(TAG, "succcess");
}
#Override
public void onError() {
Log.i(TAG, "error");
}
}
);
I'm making a list of links and for that I have made a custom adapter, but the list is not ready when the adapter starts so I get the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
this is because when the adapter is started the list is empty, and just moments after the list is filled but it's too late here is my code:
UPDATE: the code has been changed so now I du not get the error but it doesn't run getView in the adapter:
public class Controller extends Activity {
private String TAG = Controller.class.getSimpleName();
private String http;
CustomAdapter adapter;
public Controller con = null;
private ListView lv;
private static String url;
ArrayList<Selfservice> linkList = new ArrayList<Selfservice>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
con = this;
http = this.getString(R.string.http);
url = this.getString(R.string.path1);
new GetLinks().execute();
lv = (ListView)findViewById(R.id.list);
//Resources res = getResources();
//adapter = new CustomAdapter(con, linkList, res);
//lv.setAdapter(adapter);
}
private class GetLinks extends AsyncTask<Void, Void, List<Selfservice>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Selfservice> doInBackground(Void... arg0) {
Document doc;
Elements links;
List<Selfservice> returnList = null;
try {
doc = Jsoup.connect(url).timeout(0).get();
links = doc.getElementsByClass("processlink");
returnList = ParseHTML(links);
} catch (IOException e) {
e.printStackTrace();
}
return returnList;
}
#Override
protected void onPostExecute(final List<Selfservice> result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("");
toolbar.setSubtitle("");
Resources res = getResources();
Log.e(TAG, linkList.toString());
linkList = (ArrayList<Selfservice>) result;
adapter = new CustomAdapter(con, result, res);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
});
}
}
and my adapter:
public class CustomAdapter extends BaseAdapter implements OnClickListener {
private String TAG = CustomAdapter.class.getSimpleName();
Context context;
List<Selfservice> data;
private Activity activity;
public Resources res;
Selfservice self = null;
private static LayoutInflater inflater;
int layoutResourceId = 0;
public CustomAdapter(Activity act, List<Selfservice> dataList, Resources resources) {
res = resources;
activity = act;
data = dataList;
}
private class Holder {
TextView title;
TextView link;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int pos) {
return pos;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = convertView;
Holder holder;
if(rowView == null){
rowView = inflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.title = (TextView) rowView.findViewById(R.id.title);
holder.link = (TextView) rowView.findViewById(R.id.link);
rowView.setTag(holder);
}else{
holder = (Holder)rowView.getTag();
}
if(data.size()<=0){
holder.title.setText("did not work");
}else{
self = null;
self = (Selfservice) data.get(position);
holder.title.setText(self.getTitle());
holder.link.setText(self.getLink());
Log.i(TAG, "adapter");
rowView.setOnClickListener(new OnItemClickListener(position));
}
return rowView;
}
#Override
public void onClick(View v){
Log.v("CustomAdapter", "row clicked");
}
private class OnItemClickListener implements OnClickListener{
private int mPos;
OnItemClickListener(int position){
mPos = position;
}
#Override
public void onClick(View arg0){
Controller con = (Controller)activity;
con.onItemClick(mPos);
}
}
}
So How do I get the adapter to wait to the list is full?
firstly use ArrayAdapter<Selfservice> instead of BaseAdapter
use constructor
public CustomAdapter(Context context, int resource, List<Selfservice> objects) {
super(context, resource, objects);
data = objects;
}
then override only two methods
public int getCount()
public View getView(int position, View convertView, ViewGroup parent)
then return list.size() in getCount()
in getView() method
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, null);
}
in doInBackground() method in the try block
instead of linkList = ParseHTML(links);
do linkList.addAll(ParseHTML(links));
and in onPostExcecute() method
adapter.notifyDatasetChanged(); in the ui thread
You can create the adapter in the onPostExecute;
Change the Async Task to this:
private class GetLinks extends AsyncTask<Void, Void, List<Selfservice>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
Document doc;
Elements links;
List<Selfservice> returnList
try {
doc = Jsoup.connect(url).timeout(10000).get();
links = doc.getElementsByClass("processlink");
returnList = ParseHTML(links);
} catch (IOException e) {
e.printStackTrace();
}
return returnList;
}
#Override
protected void onPostExecute(List<Selfservice> result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("");
toolbar.setSubtitle("");
linkList = result
adapter = new CustomAdapter(con, result, res);
lv.setAdapter(adapter);
}
});
}
This way you will only create the adapter when your list is ready.
Edit:
You are not creating the variable context inside your adapter. Change your constructor to this:
public CustomAdapter(Context context, Activity act, List<Selfservice> dataList, Resources resources) {
res = resources;
activity = act;
data = dataList;
this.context = context;
}
And you will stop seeing the NullPointerExecption
I am using recyclerview adapter for my fragment, but my list is not getting shown as the onCreateViewHolder() and onBindViewHolder() are not getting called. Please let me know what is the issue with my code?
MyFragment code :
public class MyFragment extends Fragment {
private Integer mCurrentPage = 1;
private Integer mChosenOrder=0;
ArrayList<MyParcelableObject> mMyList;
private RecyclerView mRecyclerView;
MyAdapter mMyAdapter;
public MyFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mRecyclerView= (RecyclerView) rootView.findViewById(R.id.gridview_movies);
mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
Log.e(LOG_TAG, "In oncreateview");
if (savedInstanceState != null && savedInstanceState.getParcelableArrayList(ConstantUtil.My_LIST_KEY) != null) {
mMyList = savedInstanceState.getParcelableArrayList(ConstantUtil.My_LIST_KEY);
} else {
mMyList = new ArrayList<>();
}
new MyTask(getActivity(), mMyList,mMyAdapter).execute(mChosenOrder);
mMyAdapter = new MyAdapter(getActivity(),mMyList);
Log.e(LOG_TAG,"Adapter size oncreateview"+mMyAdapter.getItemCount());
mRecyclerView.setAdapter(mMyAdapter);
Log.e(LOG_TAG, "In oncreateview after attaching adapter");
return rootView;
}
#Override
public void onStart() {
super.onStart();
populate();
}
private void populate() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (prefs != null) {
String order = prefs.getString(getString(R.string.sorting_order), getString(R.string.pref_defaultValue));
int order_value = Integer.parseInt(order);
if (order_value >= 0) {
Resources resources = getResources();
mChosenOrder = Integer.parseInt(resources.getStringArray(R.array.pref_sorting_values)[order_value]);
} else {
mChosenOrder = order_value;
}
} else {
mChosenOrder = Integer.parseInt(getString(R.string.pref_defaultValue));
}
new MyTask(getActivity(),mMyList,mMyAdapter).execute(mChosenOrder);
Log.e(LOG_TAG,"populate Adapter size "+mMyAdapter.getItemCount());
mRecyclerView.setAdapter(mMyAdapter);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(ConstantUtil.My_LIST_KEY, mMyList);
}
}
Async Task code
public class MyTask extends AsyncTask<Integer, Void, MyParcelableObject[]> {
private Context context;
private List<MyParcelableObject> mMyParcelableObjects;
private RecyclerView recyclerView;
MyAdapter myAdapter;
public MyTask(Context context, List<MyParcelableObject> myParcelableObjects,MyAdapter myAdapter) {
this.context = context;
mMyParcelableObjects = myParcelableObjects;
this.myAdapter = myAdapter;
//this.imageAdapter = imageAdapter;
this.recyclerView = recyclerView;
}
#Override
protected MyParcelableObject[] doInBackground(Integer... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String myStr[] = null;
// Will contain the raw JSON response as a string.
String myStrJsonStr = null;
Uri buildUri = null;
MyParcelableObject[] myParcelableObjects = null;
//try {
// Context context = getApplicationContext();
ArrayList<MyParcelableObject> myParcelableObjectArrayList = null;
String[] sortOrder = context.getResources().getStringArray(R.array.pref_sorting_values);
int sort = Integer.parseInt(sortOrder[0]);
myParcelableObjectArrayList = getJsonFromUri(params[0]); //correctly gets the json array
if (myParcelableObjectArrayList != null) {
myParcelableObjects = myParcelableObjectArrayList.toArray(new MyParcelableObject[myParcelableObjectArrayList.size()]);
return myParcelableObjects;
return null;
}
/**
* #param results
*/
#Override
protected void onPostExecute(MyParcelableObject[] results) {
Log.e(LOG_TAG, "In onPostExecute");
if (results != null) {
mMyParcelableObjects = Arrays.asList(results);
myAdapter = new MyAdapter(context,mMyParcelableObjects);
Log.e(LOG_TAG,"adapter size"+myAdapter.getItemCount());
myAdapter.notifyDataSetChanged();
}
}
Adapter code
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
List<MyParcelableObject> mParcelableObjects;
ViewHolder mViewHolder;
Context mContext;
public MyAdapter(Context context, List<MyParcelableObject> parcelableObjects) {
mParcelableObjects = parcelableObjects;
mContext=context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public ViewHolder(View view) {
super(view);
mImageView = (ImageView) view.findViewById(R.id.movie_content_imageview);
}
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("LOG_TAG","in on onCreateViewHolder");
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.content_main, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
Log.e("LOG_TAG","in on onBindViewHolder");
String myPoster = null;
MyParcelableObject myParcelableObject = mParcelableObjects.get(position);
if (myParcelableObject.poster_path != null) {
myPoster = myParcelableObject.poster_path.replaceAll("/", "");
}
Uri uri = Uri.parse(ConstantUtil.POSTER_URL).buildUpon().
appendPath(ConstantUtil.W342_SIZE).
appendPath(myPoster).build();
Picasso.with(mContext).load(uri).placeholder(R.drawable.resource_notfound).error(R.drawable.resource_notfound).into(mViewHolder.mImageView);
}
#Override
public int getItemCount() {
return mParcelableObjects.size();
}
}
You are not getting value because your list is empty.
replace this
new MyTask(getActivity(), mMyList,mMyAdapter).execute(mChosenOrder);
to this
mMyList = new MyTask(getActivity(), mMyList,mMyAdapter).execute(mChosenOrder).get();
i have problem with listview... i'm trying to add OnClickListener but in still doesn't work. I want to display another activity after click. Can somebody help me? I know that there are many of example, but it's doesn't work for my appl or i don't know how to use it in my example...
This is my LocationAdapter class:
public class LocationAdapter extends ArrayAdapter<LocationModel> {
int resource;
String response;
Context context;
private LayoutInflater mInflater;
public LocationAdapter(Context context, int resource, List<LocationModel> objects) {
super(context, resource, objects);
this.resource = resource;
mInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView titleGameName;
TextView distanceGame;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
LocationModel lm = (LocationModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.titleGameName = (TextView) convertView
.findViewById(R.id.it_location_title);
holder.distanceGame = (TextView) convertView
.findViewById(R.id.it_location_distance);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleGameName.setText(lm.getGameName());
holder.distanceGame.setText(lm.getGameDistance()+" km");
return convertView;
}
}
This is my mainListView class:
public class SelectGameActivity extends Activity {
LocationManager lm;
GeoPoint userLocation;
ArrayList<LocationModel> locationArray = null;
LocationAdapter locationAdapter;
LocationList list;
ListView lv;
TextView loadingText;
TextView sprawdz;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectgame);
lv = (ListView) findViewById(R.id.list_nearme);
locationArray = new ArrayList<LocationModel>();
locationAdapter = new LocationAdapter(SelectGameActivity.this, R.layout.item, locationArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(locationAdapter);
lv.setItemsCanFocus(true);
String serverName = getResources().getString(R.string.serverAdress);
ApplicationController AC = (ApplicationController)getApplicationContext();
String idPlayer = AC.getIdPlayer();
int latitude = AC.getCurrentPositionLat();
int longitude = AC.getCurrentPositionLon();
int maxDistance = 99999999;
try {
new LocationSync().execute("myserverName");
} catch(Exception e) {}
}
//this is connection with json
private class LocationSync extends AsyncTask<String, Integer, LocationList> {
protected LocationList doInBackground(String... urls) {
LocationList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, LocationList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(LocationList loclist) {
for(LocationModel lm : loclist.getLocations())
{
locationArray.add(lm);
}
locationAdapter.notifyDataSetChanged();
}
}
EDIT:: I have second problem... i want to get id from item (items are downloading from json url) This is my list:
I want to get for example: ID:159 for first item and send it to nextActivity.
I have also the controllerClass.java where i'm setting and getting selectedIdGame:
public String getIdGameSelected() {
return idGame;
}
public void setIdGameSelected(String idGame) {
this.idGame = idGame;
}
Is it good idea? Thanks for help.
Ok, it's done. i used:
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
String idGame = (String) ((TextView) v.findViewById(R.id.idGameSelected)).getText();
Thanks, Michal.
You could define an onItemClick on your adapter instance (i.e. in mainListView.java, just after lv.setAdapter):
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
Intent i = new Intent(v.getContext(), NextActivity.class);
startActivity(i);
}
});
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Intent i = new Intent(view.getContext(), NextActivity.class);
startActivity(i);
}
});
I don't know why this wouldn't work, put it after the try{}catch{} block.