I am getting data from an XML uploaded on a website. I want to display the text from the XML in a custom ListView, which has two TextViews. The 'title' should go into the upper TextView and the 'guid' into the lower TextView. I'm not sure how I should go about doing this. I've written the following Custom Adapter.
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private ArrayList list;
private LayoutInflater layoutInflater;
public CustomAdapter(Context context, ArrayList list) {
this.list= list;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.layout_list_row, null);
holder = new ViewHolder();
holder.backgroundImage = (ImageView) convertView.findViewById(R.id.backgroundImage);
holder.topText = (TextView) convertView.findViewById(R.id.topText);
holder.bottomText = (TextView) convertView.findViewById(R.id.bottomText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
DiscourseItem discourseItem = (DiscourseItem) discourseList.get(position);
holder.topText.setText(discourseItem.getTopText());
holder.bottomText.setText(discourseItem.getBottomText());
return convertView;
}
static class ViewHolder {
ImageView backgroundImage;
TextView topText; //This should display the text in the 'title' field
TextView bottomText; //This should display the text in the 'guid' field
}
}
I'm currently able to display the two separately in separate ListViews with normal ArrayAdapters. Here's the code I've written.
XMLParser.java
public class XMLParser extends AsyncTask {
private URL url;
public ArrayList<String> title = new ArrayList<>();
public ArrayList<String> guid = new ArrayList<>();
#Override
protected Object doInBackground(Object[] objects) {
try {
url = new URL(removed);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), null);
boolean insideItem = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")){
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")){
if (insideItem)
title.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("guid")){
if (insideItem)
guid.add(xpp.nextText());
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem = false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e){
e.printStackTrace();
} catch (XmlPullParserException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
public InputStream getInputStream(URL url){
try {
return url.openConnection().getInputStream();
} catch (IOException e){
e.printStackTrace();
}
return null;
}
public ArrayList<String> titles(){
return title;
}
public ArrayList<String> guids(){
return guid;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parser = new XMLParser();
parser.execute();
title = parser.titles();
guid = parser.guids();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
discourseList = getDiscourseList();
}
}, 2000);
}
});
ListView listView = (ListView) findViewById(R.id.discourseList);
listView.setAdapter(new CustomAdapter(this, discourseList));
}
private ArrayList<DiscourseItem> getDiscourseList() {
ArrayList<DiscourseItem> listData = new ArrayList<DiscourseItem>();
String[] topText = new String[title.size()];
topText = title.toArray(topText);
String[] bottomText = new String[guid.size()];
bottomText = guid.toArray(bottomText);
for (int i = 0; i <= title.size(); i++) {
try {
DiscourseItem discourseItem = new DiscourseItem();
discourseItem.setTopText(topText[i]);
discourseItem.setBottomText(bottomText[i]);
listData.add(discourseItem);
} catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
return listData;
}
}
Edit :
I've made the above changes. Now when the parser runs and calls getDiscourseList(), it throws the following error at discourseItem.setTopText(topText[i]); :
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
You can create wrapper class for your upper and bottom values ( something like this, consider another name as I don't know the context of your data):
public class TitleGuidPair {
private final String title;
private final String guid;
public TitleGuidPair(String title, String guid) {
this.title = title;
this.guid = guid;
}
//getters
}
And then parse your result to ArrayList of TitleGuidPair. If you want to keep your parsing algorithm you can make some post-processing and build your TitleGuidPairs afterwards from the two lists that you have.
Having that step behind just pass to your adapter List of TitleGuidPairs and in the getView method set top and bottom text like
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.layout_list_row, null);
holder = new ViewHolder();
holder.backgroundImage = (ImageView) convertView.findViewById(R.id.backgroundImage);
holder.topText = (TextView) convertView.findViewById(R.id.topText);
holder.bottomText = (TextView) convertView.findViewById(R.id.bottomText);
TitleGuidPair titleGuidPair = list.get(position);
holder.topText.setText(titleGuidPair.getTitle());
holder.bottomText.setText(titleGuidPair.getGuid());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
Related
I am getting data from the SQL database to the android Expandable listview.
All of my data is correct except the listview group is repeated the same amount of the listview children.
I have no idea why and I have tried everything that came into my mind.
Anyways I am using 2 queries!
one to get the group and one to get the group children!
Here is my code: AsyncTask:
private class SyncData extends AsyncTask<String, String, String> {
String msg;
#Override
protected void onPreExecute() //Starts the progress dailog
{
System.out.println("Start");
//lottieAnimationView.playAnimation();
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
String query = "SELECT SalesInvoice.SalesInvoiceID,SalesInvoice.SalesInvoiceSerial,SalesInvoice.SalesInvoiceDate,SalesInvoice.SalesInvoiceItemCount,SalesInvoice.SalesInvoiceTotal,SalesInvoice.SalesInvoiceTaxs,SalesInvoice.SalesInvoiceLastTotal,SalesInvoice.SalesInvoiceBranchID FROM SalesInvoice where SalesInvoiceID = '321' AND SalesInvoiceBranchID = '2'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
ClassListItems classListItems = new ClassListItems(rs.getString("SalesInvoiceSerial"),rs.getString("SalesInvoiceDate"),rs.getString("SalesInvoiceItemCount"),rs.getString("salesInvoiceTotal"),rs.getString("SalesInvoiceTaxs"),rs.getString("SalesInvoiceLastTotal"));
String query2 = "SELECT SalesProductName FROM SalesInvoiceDetail WHERE SalesInvoiceID = '"+rs.getString("SalesInvoiceID")+"'";
Statement stmt2 = conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
if (rs2 != null){
while (rs2.next()){
System.out.println("ssss");
classListItems.getChildItemList().add(new ChildItem(rs2.getString("SalesProductName")));
itemArrayList.add(classListItems);
}
msg = "Found";
success = true;
}else {
msg = "Not Found";
success = false;
}
//Picasso.with(agzakhana_mainAr.this).load(rs.getString("SpecialityIcon")).into(specialityicon);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
//progress2.hideProgress();
progressDialog.hide();
if (msg!=null){
Toast.makeText(MainActivity.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
System.out.println("EndNotSuccess");
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, MainActivity.this);
exlistView21.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
exlistView21.setAdapter(myAppAdapter);
System.out.println("End");
} catch (Exception ex) {
}
}
}
}
Adapter:
public class MyAppAdapter extends BaseExpandableListAdapter//has a class viewholder which holds
{
public class ViewHolder {
TextView invoicenum;
TextView date;
TextView itemscount;
TextView total;
TextView tax;
TextView lasttotal;
TextView textchild;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
System.out.println("called");
}
#Override
public int getGroupCount() {
return parkingList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return parkingList.get(groupPosition).getChildItemList().size();
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return parkingList.get(groupPosition).getChildItemList().get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View rowView = convertView;
MyAppAdapter.ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_items, parent, false);
viewHolder = new MyAppAdapter.ViewHolder();
//initialize our labels
viewHolder.invoicenum = (TextView) rowView.findViewById(R.id.invoicenum);
viewHolder.date = (TextView) rowView.findViewById(R.id.date);
viewHolder.itemscount = (TextView) rowView.findViewById(R.id.itemcount);
viewHolder.total = (TextView) rowView.findViewById(R.id.total);
viewHolder.tax = (TextView) rowView.findViewById(R.id.tax);
viewHolder.lasttotal = (TextView) rowView.findViewById(R.id.lasttotal);
rowView.setTag(viewHolder);
} else {
viewHolder = (MyAppAdapter.ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.invoicenum.setText(parkingList.get(groupPosition).getSalesInvoiceSerial());
viewHolder.itemscount.setText(parkingList.get(groupPosition).getSalesInvoiceItemCount());
viewHolder.date.setText(parkingList.get(groupPosition).getSalesInvoiceDate());
viewHolder.total.setText(parkingList.get(groupPosition).getSalesInvoiceTotal());
viewHolder.lasttotal.setText(parkingList.get(groupPosition).getSalesInvoiceLastTotal());
viewHolder.tax.setText(parkingList.get(groupPosition).getSalesInvoiceTax());
System.out.println("PARENT IS: "+parkingList.get(groupPosition).getSalesInvoiceSerial());
// Picasso.with(context).load(parkingList.get(position).getDiscountimage()).into(viewHolder.imagediscount);
exlistView21.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
}
});
return rowView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View resultView = convertView;
ViewHolder holder;
LayoutInflater inflater = getLayoutInflater();
if (resultView == null) {
resultView = inflater.inflate(R.layout.listchildren, null); //TODO change layout id
holder = new ViewHolder();
holder.textchild = (TextView) resultView.findViewById(R.id.child); //TODO change view id
resultView.setTag(holder);
} else {
holder = (ViewHolder) resultView.getTag();
}
System.out.println("CHILD IS: "+parkingList.get(childPosition).getChildItemList().get(childPosition).getSs());
holder.textchild.setText(parkingList.get(childPosition).getChildItemList().get(childPosition).getSs());
return resultView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
// public void filter(String charText) {
// charText = charText.toLowerCase(Locale.getDefault());
// itemArrayList.clear();
// if (charText.length() == 0) {
// itemArrayList.addAll(arraylist);
//
// } else {
// for (ClassListItems2 st : arraylist) {
// if (st.getSpecialityname().toLowerCase(Locale.getDefault()).contains(charText)) {
// itemArrayList.add(st);
// }
//
// }
// }
// notifyDataSetChanged();
// }
}
}
How do i sort alphabetically the files of my listView?
I'm using a custom adapter, already try several things but nothing is working i been reading and i think i have to make a adapter list? If i'm right, can someone help me yo integrate the list adapter to my code. Is a list view using a custom a adapter an a datamodel.
MainActivity.java
ArrayList<DataModel> dataModels;
ListView list2;
private static CustomAdapter adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout rootView = (RelativeLayout) findViewById(id.relativeLayout1);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
rootView.setSystemUiVisibility(8);
final File carpeta = new File("/storage/emulated/0/Android/data/cc.openframeworks.androidMultiOFActivitiesExample/files/xml");
dataModels= new ArrayList<>();
listarFicherosPorCarpeta(carpeta);
ficheros = list.toArray(new String[list.size()]);
final List<String> list = new ArrayList<String>();
// dataModels.add(new DataModel("Apple Pie", "Android 1.0"));
for (int i = 0; i < ficheros.length; i++) {
dataModels.add(new DataModel(ficheros[i], fecha[i]));
}
adapter= new CustomAdapter(dataModels,getApplicationContext());
list2.setAdapter(adapter);
}
List<String> list = new ArrayList<String>();
public void listarFicherosPorCarpeta(final File carpeta) {
for (final File ficheroEntrada: carpeta.listFiles()) {
if (ficheroEntrada.isDirectory()) {
listarFicherosPorCarpeta(ficheroEntrada);
} else {
System.out.println(ficheroEntrada.getName());
list.add(ficheroEntrada.getName());
}
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<DataModel> {
private ArrayList<DataModel> dataSet;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtTitle;
TextView txtFecha;
}
public CustomAdapter(ArrayList<DataModel> data, Context context) {
super(context, R.layout.rowlayout, data);
this.dataSet = data;
this.mContext=context;
}
private int lastPosition = -1;
private String convertStringArrayToString(String[] stringArray) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < stringArray.length; i++) {
String item = stringArray[i];
sb.append(item).append("\n");
}
String result = sb.toString();
if (result.endsWith("\n")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
DataModel dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.rowlayout, parent, false);
viewHolder.txtTitle = (TextView) convertView.findViewById(R.id.listtext);
viewHolder.txtFecha = (TextView) convertView.findViewById(R.id.fechatxt);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtTitle.setTextColor(Color.parseColor("#015D99"));
viewHolder.txtTitle.setHeight(125);
viewHolder.txtTitle.setText(dataModel.getFicheros());
viewHolder.txtFecha.setText(dataModel.getFecha());
// Return the completed view to render on screen
return convertView;
}
}
DataModel.java
public class DataModel {
String ficheros;
String fecha;
public DataModel(String ficheros, String fecha) {
this.ficheros = ficheros;
this.fecha = fecha;
}
public String getFicheros() {
return ficheros;
}
public String getFecha() {
return fecha;
}
}
error: unreported exception ParseException; must be caught or declared to be thrown
org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details.
at >org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:104)
You can sort your arraylist before pass it to your adapter. like the following.
// ...... your other codes
for (int i = 0; i < ficheros.length; i++) {
dataModels.add(new DataModel(ficheros[i], fecha[i]));
}
// here you can sort your list like the following
Collections.sort(dataModels, new Comparator<DataModel>(){
public int compare(DataModel lhs, DataModel rhs){
return lhs.getFicheros().compareTo(rhs.getFicheros());
}
});
adapter= new CustomAdapter(dataModels,getApplicationContext());
list2.setAdapter(adapter);
And one more thing you have to add your listview to your rootView.
Update
To sort your list by date, you can do the following.
try {
// you can sort your list by date like the following
Collections.sort(dataModels, new Comparator<DataModel>(){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
public int compare(DataModel lhs, DataModel rhs){
try{
return dateFormat.parse(lhs.getFecha()).compareTo(dateFormat.parse(rhs.getFecha()));
}catch (Exception e) {
// handle your exception here.
Log.e("TAG", "Exception : "+e.toString());
return 0;
}
}
});
}
I have lots of questions that I didn't find answers to.
First of all, I have two tables in MS Sql server, one is called country that contains country id and country name, and one is called family which contains country id, family id, family name and family info. The problem I am facing is how can I write a query in Java Android that gets the id of the country and compare it with the id of the country in the families table and then for each country there is its own family.
I have tried inner joins but couldn't know how to do it.
Here is my code so far:
public class InsideCountries extends AppCompatActivity {
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
private ListView listView;
private TextView ttl;// Listview
private boolean success = false; // boolean
private ConnectionClass connectionClass; //Connection Class Variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inside_countries);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ttl = (TextView) findViewById(R.id.title) ;
ttl.setText(getIntent().getStringExtra("CountriesName"));
listView = (ListView) findViewById(R.id.listvieww); //Listview Declaration
connectionClass = new ConnectionClass(); // Connection Class Initialization
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String> {
String msg = "No Data Found";
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(InsideCountries.this, "Synchronising",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
msg = "Please Check Your Connection";
success = false;
} else {
// Change below query according to your own database.
String query = "query here";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("name")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch(Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute (String
msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
Toast.makeText(InsideCountries.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, InsideCountries.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter //has a class viewholder which holds
{
public class ViewHolder
{
TextView textName;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context)
{
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder= null;
if (rowView == null)
{
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_content, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = (TextView) rowView.findViewById(R.id.textName);
rowView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getName()+"");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(InsideCountries.this,Inside_Families.class);
intent.putExtra("Family",parkingList.get(position).getName());
startActivity(intent);
}
});
return rowView;
}
}
}
Any help would be apreciated!?
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 write client for kaltura media platform.
I have an activity "Video". In this activity I must display list of video with thumbnails
First of all, I download list of videos using kaltura api, and this works fine. Every video entry have a field thumbnailUrl, which point out to thumbnail for video.
When I download this thumbnails for videos, it's(thumbnails) downloads in incorrect order, some thumbnails not downloaded, some thumbnails repeated for other video, and some not downloaded.
This is code of callback if downloadind videos:
private void handleFetchvideoListTask(List<VideoObject> videoObjects){
LinearLayout videoListProgressBarContainer = (LinearLayout)mActivity.findViewById(R.id.videoListProgressBarContainer);
LinearLayout videoListViewContainer = (LinearLayout)mActivity.findViewById(R.id.videoListViewContainer);
videoListProgressBarContainer.setVisibility(View.GONE);
videoListViewContainer.setVisibility(View.VISIBLE);
ListView listView = (ListView)videoListViewContainer.findViewById(R.id.videoListView);
VideoListAdapter adapter = new VideoListAdapter((LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
adapter.setList(videoObjects);
listView.setAdapter(adapter);
DownloadThumbnailsTask task = new DownloadThumbnailsTask(videoObjects, adapter);
task.execute();
}
This is code of DownloadThumbnailsTask:
public class DownloadThumbnailsTask extends AsyncTask<List<VideoObject>, VideoObject, Void>{
private List<VideoObject> videoObjectList = null;
private List<VideoObject> toProcess = null;
private VideoListAdapter adapter = null;
public DownloadThumbnailsTask(List<VideoObject> videoObjectList, VideoListAdapter adapter){
this.videoObjectList = videoObjectList;
this.toProcess = new ArrayList<VideoObject>(videoObjectList);
this.adapter = adapter;
}
#Override
protected Void doInBackground(List<VideoObject>... lists) {
for(int i=0; i<toProcess.size(); i++){
VideoObject item = videoObjectList.get(i);
String urldisplay = item.getThumbnailUrl();
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
item.setThumbnail(mIcon11);
mIcon11 = null;
publishProgress(item);
}
return null;
}
#Override
protected void onProgressUpdate(VideoObject... values) {
if(values != null && values.length > 0){
VideoObject item = values[0];
videoObjectList.remove(item);
videoObjectList.add(item);
adapter.setList(videoObjectList);
adapter.notifyDataSetChanged();
}
}
#Override
protected void onPostExecute(Void aVoid) {
this.toProcess.clear();
this.toProcess = null;
}
}
This is code of adapter:
public class VideoListAdapter extends BaseAdapter {
private List<VideoObject> list;
private LayoutInflater layoutInflater;
public VideoListAdapter(LayoutInflater layoutInflater){
this.layoutInflater = layoutInflater;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return list.get(i).getId();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null){
view = layoutInflater.inflate(R.layout.list_item_video, viewGroup, false);
}
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
VideoObject item = getVideoObjectItem(i);
viewHolder.duration.setText(item.getFormattedDuration());
viewHolder.title.setText(item.getName());
if(item.getThumbnail() != null){
viewHolder.thumbnail.setImageBitmap(item.getThumbnail());
}
return view;
}
private VideoObject getVideoObjectItem(int position){
return (VideoObject) getItem(position);
}
public List<VideoObject> getList() {
return list;
}
public void setList(List<VideoObject> list) {
this.list = list;
}
public static class ViewHolder {
public final ImageView thumbnail;
public final TextView title;
public final TextView duration;
public ViewHolder(View view) {
this.thumbnail = (ImageView)view.findViewById(R.id.imgVideoThumbnail);
this.title = (TextView)view.findViewById(R.id.txtVideoName);
this.duration = (TextView)view.findViewById(R.id.txtVideoDuration);
}
}
}
And this is result of my code:
I noticed two things:
Inside doInBackground you are waiting
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
to complete before downloading the next image.
Try this:
protected Void doInBackground(List<VideoObject>... lists) {
for(final int i=0; i<toProcess.size(); i++){
try {
new Thread(){
#Override
public void run() {
VideoObject item = videoObjectList.get(i);
String urldisplay = item.getThumbnailUrl();
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
item.setThumbnail(mIcon11);
publishProgress(item);
}
}.start();
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
}
return null;
}
#Override
protected void onProgressUpdate(VideoObject... values) {
adapter.notifyDataSetChanged();
}
I think this two lines is the problem:
videoObjectList.remove(item);
videoObjectList.add(item);
You're removing an item and adding again at the bottom. Just call notifyDataSetChanged after setting the bitmap.
Inside getView you're creating a new ViewHolder every time.
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null){
view = layoutInflater.inflate(R.layout.list_item_video, viewGroup, false);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else{
viewHolder = view.getTag();
}
VideoObject item = getVideoObjectItem(i);
viewHolder.duration.setText(item.getFormattedDuration());
viewHolder.title.setText(item.getName());
if(item.getThumbnail() != null){
viewHolder.thumbnail.setImageBitmap(item.getThumbnail());
}
return view;
}
Do you get anything in your logcat? Maybe opening the stream or decoding fails. Are the images large?