I'm trying to read everything in my external text file and put it into an array list that is send to another class via a parcel class. Although I can get the strings set on textview, but not the image.
One of the lines in my external text file looks like:
McDonalds| Any McDonalds outlet| Applicable to any lunch meal set| Buy 1 get 1 free| 1 Aug - 31 Aug| RM 32.00| RM 16.00| icon_nandos.png
MainActivity.java:
public class MainActivity extends AppCompatActivity implements listAdapter.sendInfo{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_fragment lf = new list_fragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.mainAct, lf);
fragmentTransaction.commit();
}
#Override
public void detailInfo(outletData outDat, int pos) {
fragmentDetail fd = fragmentDetail.newInstance(outDat);
getSupportFragmentManager().beginTransaction()
.replace(R.id.mainAct, fd)
.addToBackStack(null)
.commit();
}
}
list_fragment.java:
public class list_fragment extends Fragment {
ArrayList<outletData> outletDatas = new ArrayList<outletData>();
BufferedReader bufferedReader = null;
String food;
public View onCreateView( LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
RecyclerView recyclerView = view.findViewById(R.id.fragRecycler);
outletDatas.clear();
try{
bufferedReader = new BufferedReader(new
InputStreamReader(getContext().getAssets().open("food_catalog.txt")));
while ((food = bufferedReader.readLine())!=null) {
if (!food.equals("")) {
String[] foodInfo = food.split("\\|");
outletDatas.add(new outletData(foodInfo[0], foodInfo[1], foodInfo[2], foodInfo[3], foodInfo[4], foodInfo[5], foodInfo[6], foodInfo[7]));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
listAdapter mylistAdapter = new listAdapter(outletDatas, getContext());
recyclerView.setAdapter(mylistAdapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
}
outletData.java:
package com.example.user.assignmentthreethree;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Parcel;
import android.os.Parcelable;
public class outletData implements Parcelable {
private String name, location, details, deals, offerPeriod, normalPrice, discountPrice, imagePath;
public outletData(String name, String location, String details, String deals, String offerPeriod, String normalPrice, String discountPrice, String imagePath) {
this.name = name;
this.location = location;
this.details = details;
this.deals = deals;
this.offerPeriod = offerPeriod;
this.normalPrice = normalPrice;
this.discountPrice = discountPrice;
this.imagePath = imagePath;
}
private outletData(Parcel in) {
name = in.readString();
location = in.readString();
details = in.readString();
deals = in.readString();
offerPeriod = in.readString();
normalPrice = in.readString();
discountPrice = in.readString();
imagePath = in.readString();
}
public static final Creator<outletData> CREATOR = new Creator<outletData>() {
#Override
public outletData createFromParcel(Parcel in) {
return new outletData(in);
}
#Override
public outletData[] newArray(int size) {
return new outletData[size];
}
};
public String getName() {
return name;
}
public String getLocation() {
return location;
}
public String getDetails() {
return details;
}
public String getDeals() {
return deals;
}
public String getOfferPeriod() {
return offerPeriod;
}
public String getNormalPrice() {
return normalPrice;
}
public String getDiscountPrice() {
return discountPrice;
}
public String getImagePath() {
return imagePath;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(location);
parcel.writeString(details);
parcel.writeString(deals);
parcel.writeString(offerPeriod);
parcel.writeString(normalPrice);
parcel.writeString(discountPrice);
parcel.writeString(imagePath);
}
}
listAdapter.java:
public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
ArrayList<outletData> outletDataFromFragment;
RecyclerView recyclerView;
Context mContext;
listAdapter(ArrayList<outletData> outletDataFromFragment) {
this.outletDataFromFragment = outletDataFromFragment;
}
#Override
public listAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
this.mContext = viewGroup.getContext();
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull listAdapter.ViewHolder viewHolder, int i) {
outletData data = outletDataFromFragment.get(i);
viewHolder.listName.setText(data.getName());
viewHolder.listDeal.setText(data.getDeals());
viewHolder.listOffer.setText(data.getOfferPeriod());
// viewHolder.listImg.setImageURI(Uri.parse(data.getImagePath()));
try {
InputStream ims = mContext.getAssets().open(""+data.getImagePath().trim());
Drawable d = Drawable.createFromStream(ims, null);
viewHolder.listImg.setImageDrawable(d);
ims.close();
} catch (IOException ex) {
return;
}
}
#Override
public int getItemCount() {
return outletDataFromFragment.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView listName, listDeal, listOffer;
ImageView listImg;
public ViewHolder(View itemView) {
super(itemView);
listName = (TextView)itemView.findViewById(R.id.txtName);
listDeal = (TextView)itemView.findViewById(R.id.txtDeals);
listOffer = (TextView)itemView.findViewById(R.id.txtOffer);
listImg = (ImageView)itemView.findViewById(R.id.imgFood);
recyclerView = (RecyclerView)itemView.findViewById(R.id.reCyclerView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
((sendInfo)view.getContext()).detailInfo(outletDataFromFragment.get(getLayoutPosition()), getLayoutPosition());
}
}
interface sendInfo {
void detailInfo(outletData outletData, int pos);
}
}
fragmentDetail.java:
public class fragmentDetail extends Fragment {
TextView fragName, fragDeal, fragOffer, fragDetail, fragOldPrice, fragNewPrice, fragLocation;
ImageView fragImage;
outletData OD;
Bundle bundle;
public fragmentDetail() {}
public static fragmentDetail newInstance(outletData oData) {
fragmentDetail fragmentDetail = new fragmentDetail();
Bundle b = new Bundle();
b.putParcelable("pData", oData);
fragmentDetail.setArguments(b);
return fragmentDetail;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = this.getArguments();
OD = bundle.getParcelable("pData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
fragName = (TextView)view.findViewById(R.id.frag_name);
fragDeal = (TextView)view.findViewById(R.id.frag_Deal);
fragOffer = (TextView)view.findViewById(R.id.frag_Offer);
fragDetail = (TextView)view.findViewById(R.id.frag_Detail);
fragOldPrice = (TextView)view.findViewById(R.id.frag_oldPrice);
fragNewPrice = (TextView)view.findViewById(R.id.frag_newPrice);
fragLocation = (TextView)view.findViewById(R.id.frag_location);
fragImage = (ImageView)view.findViewById(R.id.frag_image);
Toast.makeText(getContext(), OD.getImagePath(), Toast.LENGTH_LONG).show();
fragOldPrice.setPaintFlags(fragOldPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
fragName.setText(OD.getName());
fragDeal.setText(OD.getDeals());
fragOffer.setText(OD.getOfferPeriod());
fragDetail.setText(OD.getDetails());
fragOldPrice.setText(OD.getNormalPrice());
fragNewPrice.setText(OD.getDiscountPrice());
fragLocation.setText(OD.getLocation());
fragImage.setImageURI(Uri.parse(OD.getImagePath()));
return view;
}
}
Based on suggestions online I have tried trimming the string but it doesn't change the outcome. I am still learning the logic flows and syntax of Android Studio, but I don't know why its not getting the image even the images are in the same folder as the text file (Assests) and it does gets the food[7] string as icon_nandos.png when I tried printing it out.
You can try to get drawable from asset file and setting it to your imageview. Use the following code.
try {
InputStream ims = getAssets().open(""+your_image_name);
Drawable d = Drawable.createFromStream(ims, null);
mImage.setImageDrawable(d);
ims.close();
} catch(IOException ex) {
return;
}
so you need to edit your code as below.
public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
ArrayList<outletData> outletDataFromFragment;
RecyclerView recyclerView;
Context mContext;
listAdapter(ArrayList<outletData> outletDataFromFragment) {
this.outletDataFromFragment = outletDataFromFragment;
}
#Override
public listAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
this.mContext = viewGroup.getContext();
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull listAdapter.ViewHolder viewHolder, int i) {
outletData data = outletDataFromFragment.get(i);
viewHolder.listName.setText(data.getName());
viewHolder.listDeal.setText(data.getDeals());
viewHolder.listOffer.setText(data.getOfferPeriod());
try {
InputStream ims = mContext.getAssets().open(""+your_image_name);
Drawable d = Drawable.createFromStream(ims, null);
viewHolder.listImg.setImageDrawable(d);
ims.close();
} catch(IOException ex) {
return;
}
}
Related
I developed a vocabulary app that has a Recycler View in main activity and shows two column of database: unit number and Unit name.When I click on each item it goes to another activity called inner page that has 6 text views and it must show other items of that row like word definition unit number spell meaning and part of speech. But unfortunately text views are empty and it shows only one value which is unit number.Please take a look at my codes and tell me what I missed.
Here's my codes:
Main page:
public class TabWord extends Fragment {
private RecyclerView recyclerView;
private ArrayList<WordItem> items = new ArrayList<>();
private WordTab adapter;
private DatabaseHelper databaseHelper;
private Cursor cursor ;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.tab_word, container, false);
recyclerView = viewGroup.findViewById(R.id.recyclerview_word);
adapter = new WordTab(items, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
loadDatabase();
return viewGroup;
}
public void loadDatabase() {
databaseHelper = new DatabaseHelper(getActivity());
try {
databaseHelper.checkAndCopyDatabase();
databaseHelper.openDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
try {
cursor = databaseHelper.QueryData("select * from ielts");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
WordItem item = new WordItem();
item.setUnitName(cursor.getString(2));
item.setUnitNumber(cursor.getString(1));
items.add(item);
} while (cursor.moveToNext());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new WordTab(items, getActivity());
adapter.setOnTapListener(new OnTapListener() {
#Override
public void OnTapView(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
}
Adapter:
public class WordTab extends RecyclerView.Adapter<WordTab.ViewHolder> {
public static List<WordItem> wordItems;
private Context context;
private OnTapListener onTapListener;
public WordTab(List<WordItem> wordItems, Context context) {
this.wordItems = wordItems;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample_word, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
WordItem wordItem = wordItems.get(position);
holder.unitNumber.setText(wordItem.getUnitNumber());
holder.unitName.setText(wordItem.getUnitName());
holder.cardView.setId(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onTapListener != null) {
onTapListener.OnTapView(position);
int position = v.getId();
Intent intent = new Intent(context, InnerPage.class);
intent.putExtra("name", "words");
intent.putExtra("id", position + "");
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return wordItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView unitName, unitNumber;
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
unitName = itemView.findViewById(R.id.unit_name);
unitNumber = itemView.findViewById(R.id.unit_number);
cardView= itemView.findViewById(R.id.card_view_word);
}
}
public void setOnTapListener(OnTapListener onTapListener) {
this.onTapListener = onTapListener;
}
}
Model:
public class WordItem {
private int id;
private String unitNumber;
private String unitName;
private String word;
private String phonetic,pos,persian,definition;
public WordItem() {
this.unitName = unitName;
this.unitNumber = unitNumber;
this.word = word;
this.phonetic = phonetic;
this.pos = pos;
this.persian = persian;
this.definition = definition;
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public String getPersian() {
return persian;
}
public void setPersian(String persian) {
this.persian = persian;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUnitNumber() {
return unitNumber;
}
public void setUnitNumber(String unitNumber) {
this.unitNumber = unitNumber;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
}
Inner Page:
public class InnerPage extends AppCompatActivity {
private int id;
private String unitNumber,word,phonetic,pos,persian,definition;
private TextView unitTxt,wordTxt,phoneticTxt,posTxt,persianTxt,definitionTxt;
private int layoutId;
private String pageName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inner_page);
Bundle extras = getIntent().getExtras();
if (extras != null) {
layoutId = Integer.parseInt(extras.getString("id"));
pageName = extras.getString("name");
if (pageName.equals("words")){
id = WordTab.wordItems.get(layoutId).getId();
unitNumber = WordTab.wordItems.get(layoutId).getUnitNumber();
word = WordTab.wordItems.get(layoutId).getWord();
phonetic = WordTab.wordItems.get(layoutId).getPhonetic();
pos = WordTab.wordItems.get(layoutId).getPos();
persian = WordTab.wordItems.get(layoutId).getPersian();
definition = WordTab.wordItems.get(layoutId).getDefinition();
}
}
unitTxt = findViewById(R.id.unit);
wordTxt = findViewById(R.id.word);
phoneticTxt = findViewById(R.id.phonetic);
posTxt = findViewById(R.id.txtSpell);
persianTxt = findViewById(R.id.farMean);
definitionTxt = findViewById(R.id.definition);
unitTxt.setText(unitNumber);
wordTxt.setText(word);
phoneticTxt.setText(phonetic);
posTxt.setText(pos);
persianTxt.setText(persian);
definitionTxt.setText(definition);
}
}
How to Display the Local image(drawable image file) to cardview via json. I want to load image in offline rather then using picasso library
I'm using tab layout And my Frament.java
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ArrayList<Website> babyList = Website.getbabyFromFile("baby&kids.json", getActivity());
adapter = new WebsiteAdapter(this, babyList);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),2));
recyclerView.setAdapter(adapter);
}
My Website.java is
private String url;
public String imageUrl;
public Website() {
}
public Website(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public static ArrayList<Website> getbabyFromFile(String filename, Context context) {
final ArrayList<Website> babyList = new ArrayList<>();
try {
// Load data
String jsonString = loadJsonFromAsset("baby&kids.json", context);
JSONObject json = new JSONObject(jsonString);
JSONArray baby = json.getJSONArray("baby&kids");
// Get Website objects from data
for(int i = 0; i < baby.length(); i++){
Website recipe = new Website();
recipe.setUrl(baby.getJSONObject(i).getString("url"));
babyList.add(recipe);
}
} catch (JSONException e) {
e.printStackTrace();
}
return babyList;
}
private static String loadJsonFromAsset(String filename, Context context) {
String json = null;
try {
InputStream is = context.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
}
catch (java.io.IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
And this is my WebsitAdapter.java
private Fragment mContext;
// private LayoutInflater mInflater;
private ArrayList<Website> mDataSource;
OnItemClickListener mItemClickListener;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
//each data item is just a string in this case
public TextView url;
public ImageView thumbnailImageView;
public ViewHolder(View v) {
super(v);
url = (TextView) v.findViewById(R.id.websitename_id);
thumbnailImageView = (ImageView) v.findViewById(R.id.website_image_id);
v.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent detailIntent = new Intent(view.getContext(), Webview.class);
detailIntent.putExtra("url", url.getText().toString());
mContext.startActivity(detailIntent);
}
}
public interface OnItemClickListener{
public void onItemClick(View view, int Position);
}
public void SetOnItemClickListner(final OnItemClickListener mItemClickListener){
this.mItemClickListener = mItemClickListener;
}
public WebsiteAdapter(Fragment context, ArrayList<Website> items) {
mContext = context;
mDataSource = items;
// mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_item_website, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(WebsiteAdapter.ViewHolder holder, int position) {
// - get element from arraylist at this position
// - replace the contents of the view with that element
Website website = mDataSource.get(position);
holder.url.setText(website.getUrl());
//Picasso.with(mContext).load(website.imageUrl).placeholder(R.mipmap.ic_launcher).into(holder.thumbnailImageView);
}
#Override
public int getItemCount() {
return mDataSource.size();
}
And My output is
Please give me a solution that if theres is any possible ways to display images that is stored on drawable folder
If you have local images under drawable folder for all a) myntra b) firstCry c) hopscotch etc. Then you just simply need to get the correct drawable based on url.
You can create Factory class which will give you the #DrawableRes
public static #DrawableRes int getDrawable(String url){
if(url.contains("Myntra")) {
return R.drawable.myntra;
} else if(url.contains("Snapdeal")) {
return R.drawable.snapdeal;
}
// Add other if else to support other website url
}
Here is the modified onBindViewHolder method.
#Override
public void onBindViewHolder(WebsiteAdapter.ViewHolder holder, int position) {
Website website = mDataSource.get(position);
holder.url.setText(website.getUrl());
holder.thumbnailImageView.setImageResource(getDrawable(website.getUrl()));
}
[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;
}
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'm trying to use recyclerview on fragment with dummy data sample, but does not display any results in fragments that I made, but when I tried it on the activity, the desired results appear in the class activity. Here is a method fragment manager that I made to replace each fragment:
public void changeFragment(Fragment targetFragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_fragment, targetFragment)
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
and this is my current line of code to access the target fragment :
setOnItemClickListener(new DrawerItem.OnItemClickListener() {
#Override
public void onClick(DrawerItem drawerItem, long l, int i) {
changeFragment(new NewsFeedSantri().newInstance());
closeDrawer();
}
})
This is my adapter to generate dummy data :
public class NewsFeedAdapter extends RecyclerView.Adapter<NewsFeedAdapter.NewsFeedHolder> {
private List<NewsFeedItem> newsList;
public NewsFeedAdapter() {
super();
newsList = new ArrayList<NewsFeedItem>();
NewsFeedItem nf = new NewsFeedItem();
for (int i=1; i <= 20; i++) {
nf.setNewsTittle("Judul Berita");
nf.setNewsDate("20/12/2015");
nf.setNewsContent("Ini lorem ipsum dll");
newsList.add(nf);
}
}
#Override
public NewsFeedHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.base_newsfeed_item, parent, false);
NewsFeedHolder viewHolder = new NewsFeedHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(NewsFeedHolder holder, int position) {
NewsFeedItem newsfeed = newsList.get(position);
holder.viewTittle.setText(newsfeed.getNewsTittle());
holder.viewDate.setText(newsfeed.getNewsDate());
holder.viewContent.setText(newsfeed.getNewsContent());
}
#Override
public int getItemCount() {
return newsList.size();
}
public class NewsFeedHolder extends RecyclerView.ViewHolder {
protected TextView viewTittle;
protected TextView viewUrl;
protected TextView viewContent;
protected TextView viewDate;
public NewsFeedHolder(View itemView) {
super(itemView);
viewTittle = (TextView) itemView.findViewById(R.id.news_tittle);
viewDate = (TextView) itemView.findViewById(R.id.news_date);
viewContent = (TextView) itemView.findViewById(R.id.news_content);
}
}
This is NewsFeedItem class :
public class NewsFeedItem {
protected String idNewsTittle;
protected String newsTittle;
protected String newsUrl;
protected String newsContent;
protected String newsDate;
public String getIdNewsTittle() {
return idNewsTittle;
}
public void setIdNewsTittle(String idNewsTittle) {
this.idNewsTittle = idNewsTittle;
}
public String getNewsTittle() {
return newsTittle;
}
public void setNewsTittle(String newsTittle) {
this.newsTittle = newsTittle;
}
public String getNewsUrl() {
return newsUrl;
}
public void setNewsUrl(String newsUrl) {
this.newsUrl = newsUrl;
}
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
public String getNewsDate() {
return newsDate;
}
public void setNewsDate(String newsDate) {
this.newsDate = newsDate;
}
And this is my fragment :
public class NewsFeedSantri extends Fragment {
private RecyclerView recList;
public static NewsFeedSantri newInstance() {
NewsFeedSantri fragment = new NewsFeedSantri();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.base_newsfeed_rcview, container, false);
recList = (RecyclerView) rootView.findViewById(R.id.news_rcview);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
NewsFeedAdapter nfa = new NewsFeedAdapter();
recList.setAdapter(nfa);
return rootView;
} }
No error is generated, this is what makes me confused, did I miss something?