I'm pretty new new Android development. I have a class that extends Activity and I'd like to change to to a Fragment. I know as a fragment it would use onCreateView(LayoutInflater, ViewGroup, Bundle) but I'm not sure how to change my working activity to a fragment.
EDIT: I have gotten it kind of working. The problem now is that my list from the RSS feed isn't showing. I get my loading indicator and it stops once it's finished but the list doesn't show.
EDIT: Actually the list is showing, but the text is the same color as the background so I couldn't see it.
Here is my existing Activity:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ActionAlerts extends Activity {
ListView listFeed;
ProgressBar prgLoading;
TextView txtAlert;
ActionAlertsAdapter la;
static String[] title;
static String[] pubDate;
static String[] link;
String URLFeed;
URL Feed;
DocumentBuilder db;
Document doc;
NodeList nodeList;
Bundle rssBundle = new Bundle();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionalerts);
Bundle b = getIntent().getExtras();
URLFeed = b.getString("url");
la = new ActionAlertsAdapter(this);
listFeed = (ListView) findViewById(R.id.listFeed);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// ColorDrawable whiteColor = new ColorDrawable(Color.WHITE);
ColorDrawable blackColor = new ColorDrawable(Color.BLACK);
listFeed.setDivider(blackColor);
listFeed.setDividerHeight(3);
new getDataTask().execute();
listFeed.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Intent web = new Intent(ActionAlerts.this, WebBrowser.class);
rssBundle.putString("myURL", link[position]);
web.putExtras(rssBundle);
startActivity(web);
}
});
}
/** this class is used to handle thread */
public class getDataTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getDataFromFeed();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//dialog.dismiss();
prgLoading.setVisibility(8);
if(title != null){
listFeed.setVisibility(0);
listFeed.setAdapter(la);
}else{
txtAlert.setVisibility(0);
}
}
}
/*
* This code is used to get data from feed and store them
* to array attributes
*/
public void getDataFromFeed(){
try {
Feed = new URL(URLFeed);
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(Feed.openStream()));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("item");
title = new String[nodeList.getLength()];
pubDate = new String[nodeList.getLength()];
link = new String[nodeList.getLength()];
for(int i=0;i<nodeList.getLength();i++){
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList titleList = fstElmnt.getElementsByTagName("title");
Element titleElement = (Element) titleList.item(0);
titleList = titleElement.getChildNodes();
title[i] = ((Node) titleList.item(0)).getNodeValue();
NodeList pubDateList = fstElmnt.getElementsByTagName("pubDate");
Element pubDateElement = (Element) pubDateList.item(0);
pubDateList = pubDateElement.getChildNodes();
pubDate[i] = ((Node) pubDateList.item(0)).getNodeValue();
// chops off the " +0000" on date
pubDate[i] = pubDate[i].substring(0, pubDate[i].length()-14);
NodeList linkList = fstElmnt.getElementsByTagName("link");
Element linkElement = (Element) linkList.item(0);
linkList = linkElement.getChildNodes();
link[i] = ((Node) linkList.item(0)).getNodeValue();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
Here is my adapter class:
package kyfb.android.kyfb.com.kyfb;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
class ActionAlertsAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ActionAlertsAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return ActionAlertsFragment.title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null){
convertView = inflater.inflate(R.layout.item_feed, null);
holder = new ViewHolder();
holder.lytItemFeed = (RelativeLayout) convertView.findViewById(R.id.lytItemFeed);
holder.txtTitle= (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtPubDate = (TextView) convertView.findViewById(R.id.txtPubDate);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
if((position%2)!=0){
// holder.lytItemFeed.setBackgroundResource(R.drawable.row_1);
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}else{
// holder.lytItemFeed.setBackgroundResource(R.drawable.row_2);
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}
holder.txtTitle.setText(ActionAlertsFragment.title[position]);
holder.txtPubDate.setText(ActionAlertsFragment.pubDate[position]);
holder.txtTitle.setTextColor(Color.BLACK);
holder.txtPubDate.setTextColor(Color.BLACK);
return convertView;
}
static class ViewHolder {
TextView txtTitle, txtPubDate;
RelativeLayout lytItemFeed;
}
}
Here is my Fragment class that I'm trying to make from the activity class above:
package kyfb.android.kyfb.com.kyfb;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class ActionAlertsFragment extends Fragment {
ListView listFeed;
ProgressBar prgLoading;
TextView txtAlert;
ActionAlertsAdapter la;
static String[] title;
static String[] pubDate;
static String[] link;
String URLFeed;
URL Feed;
DocumentBuilder db;
Document doc;
NodeList nodeList;
Bundle rssBundle = new Bundle();
public ActionAlertsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// View rootView = inflater.inflate(R.layout.fragment_actionalerts, container, false);
View rootView = inflater.inflate(R.layout.fragment_actionalerts, null);
URLFeed = "http://kyfbnewsroom.com/category/notifications/feed";
Context ctx = rootView.getContext();
la = new ActionAlertsAdapter(ctx);
listFeed = (ListView) rootView.findViewById(R.id.listFeed);
prgLoading = (ProgressBar) rootView.findViewById(R.id.prgLoading);
txtAlert = (TextView) rootView.findViewById(R.id.txtAlert);
// ColorDrawable whiteColor = new ColorDrawable(Color.WHITE);
ColorDrawable blackColor = new ColorDrawable(Color.BLACK);
listFeed.setDivider(blackColor);
listFeed.setDividerHeight(3);
new getDataTask().execute();
listFeed.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// Intent web = new Intent(ActionAlertsFragment.this, WebBrowser.class);
// rssBundle.putString("myURL", link[position]);
// web.putExtras(rssBundle);
// startActivity(web);
}
});
return rootView;
}
/** this class is used to handle thread */
public class getDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getDataFromFeed();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//dialog.dismiss();
prgLoading.setVisibility(8);
if(title != null){
listFeed.setVisibility(0);
listFeed.setAdapter(la);
}else{
txtAlert.setVisibility(0);
}
}
}
/*
* This code is used to get data from feed and store them
* to array attributes
*/
public void getDataFromFeed(){
try {
Feed = new URL(URLFeed);
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(Feed.openStream()));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("item");
title = new String[nodeList.getLength()];
pubDate = new String[nodeList.getLength()];
link = new String[nodeList.getLength()];
for(int i=0;i<nodeList.getLength();i++){
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList titleList = fstElmnt.getElementsByTagName("title");
Element titleElement = (Element) titleList.item(0);
titleList = titleElement.getChildNodes();
title[i] = ((Node) titleList.item(0)).getNodeValue();
NodeList pubDateList = fstElmnt.getElementsByTagName("pubDate");
Element pubDateElement = (Element) pubDateList.item(0);
pubDateList = pubDateElement.getChildNodes();
pubDate[i] = ((Node) pubDateList.item(0)).getNodeValue();
// chops off the " +0000" on date
pubDate[i] = pubDate[i].substring(0, pubDate[i].length()-14);
NodeList linkList = fstElmnt.getElementsByTagName("link");
Element linkElement = (Element) linkList.item(0);
linkList = linkElement.getChildNodes();
link[i] = ((Node) linkList.item(0)).getNodeValue();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
First change this.
View rootView = inflater.inflate(R.layout.fragment_actionalerts, null);
to
View rootView = inflater.inflate(R.layout.fragment_actionalerts, container, false);
And use Fragment Context as a getActivity().
Try this:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_submenus_list, null);
....
return view;
}
And change every findViewById(...) to view.findViewById(...)
Related
Guys am abit new to android but i have developed an android application that connects to the webservice and returns an xml file...problem is i have failed to find a way of displaying this data in a list view. Please guys help and tell me how am going wrong
package com.example.testservice;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Statement extends ActionBarActivity {
Button BtnBack, BtnSend;
String AccountNumer, xmlreturn;
EditText _AccountNumer;
TextView trandate, tranType, amount;
Context context;
//private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statement);
//trandate = (TextView) findViewById(R.id.textView2);
//tranType = (TextView) findViewById(R.id.textView3);
//amount = (TextView) findViewById(R.id.textView4);
BtnBack = (Button) findViewById(R.id.button2);
BtnSend = (Button) findViewById(R.id.button1);
_AccountNumer = (EditText) findViewById(R.id.editText1);
// lv = (ListView) findViewById(R.id.listView1);
BtnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Welcome.class);
startActivity(i);
}
});
BtnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AccountNumer = _AccountNumer.getText().toString();
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
xmlreturn = WebService.StateMentWS(AccountNumer, "getStateMent");
return null;
}
#Override
protected void onPostExecute(Void result) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
ArrayList<String> listdata = new ArrayList<String>();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlreturn));
Document doc = db.parse(is);
NodeList nodeList = doc.getElementsByTagName("statementTable");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element providerID = (Element) node;
NodeList providerIDlist = providerID.getElementsByTagName("trandate");
Element providerIDelement = (Element) providerIDlist.item(0);
providerIDlist = providerIDelement.getChildNodes();
String MProviderIDL = providerIDlist.item(0).getNodeValue();
listdata.add(MProviderIDL);
Element providerName = (Element) node;
NodeList providerNamelist = providerName.getElementsByTagName("tran_type");
Element prividerNameElement = (Element) providerNamelist.item(0);
providerNamelist = prividerNameElement.getChildNodes();
AdvImglist.item(0)).getNodeValue());
String MProviderNameL = providerNamelist.item(0).getNodeValue();
MProviderNameL.toString());
listdata.add(MProviderNameL);
Element providerNamet = (Element) node;
NodeList providerNamelistt = providerNamet.getElementsByTagName("tran_type");
Element prividerNameElementt = (Element) providerNamelistt.item(0);
providerNamelist = prividerNameElementt.getChildNodes();
AdvImglist.item(0)).getNodeValue());
MProviderNameL = providerNamelist.item(0).getNodeValue();
MProviderNameL.toString());
listdata.add(MProviderNameL);
Element providerNametx = (Element) node;
NodeList providerNamets = providerNametx.getElementsByTagName("amount");
Element prividerNameElementtttx = (Element) providerNamets.item(0);
providerNamelist = prividerNameElementtttx.getChildNodes();
AdvImglist.item(0)).getNodeValue());
MProviderNameL = providerNamelist.item(0).getNodeValue();
MProviderNameL.toString());
listdata.add(MProviderNameL);
}
ListView ListView1 = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>
(context, android.R.layout.
simple_list_item_1, listdata);
adapter.setDropDownViewResource
(android.R.layout.simple_list_item_1);
ListView1.setAdapter(adapter);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.statement, menu);
return true;
}
}
when i click the button i get an exception that the application stopped working but i don't get anything logged in the logcat.
sorry for my question, I guess it's pretty simple. I have a Fragment that needs to implements an interface listener.
package com.tumta.henrique.teste;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.tumta.henrique.teste.ConsultaEntidades.*;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class EntidadeFragment extends Fragment implements ConsultaConcluidaListener {
private static final String ARG_SECTION_NUMBER = "section_number";
public EntidadeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_entidade, container, false);
new ConsultaEntidades((ConsultaEntidades)getActivity()).execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public static EntidadeFragment newInstance(int sectionNumber){
EntidadeFragment frag = new EntidadeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
frag.setArguments(args);
return frag;
}
#Override
public void onConsultaConcluida(List<String> result) {
ListView listaEntidades = (ListView) getView().findViewById(R.id.listaentidades);
ArrayAdapter arrayAdapter = new ArrayAdapter<>(getView().getContext(),android.R.layout.simple_list_item_1, result);
listaEntidades.setAdapter(arrayAdapter);
}
}
I need used to use this when it was an Activity: new ConsultaEntidades(this).execute(); But now I need to use the same line in the Frag, but I can't use this and when I use new ConsultaEntidades((ConsultaEntidades)getActivity()).execute(); It shows ~cannot cast FragmentActivity to ConsultaEntidades<br><br>ConsultaEntidades` is my class:
package com.tumta.henrique.teste;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
public class ConsultaEntidades extends AsyncTask<Void, Void, List<String>> {
private ConsultaConcluidaListener listener;
private static final String URL_STRING = "http://192.168.0.14:7001/com.henrique.rest/api/v1/status/entidade/";
public ConsultaEntidades(ConsultaConcluidaListener listener){
this.listener = listener;
}
#Override
protected List<String> doInBackground(Void... arg0) {
try {
String resultado = ConsultaServidor();
return InterpretaResultado(resultado);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private List<String> InterpretaResultado(String resultado) throws JSONException {
JSONObject object = new JSONObject(resultado);
JSONArray jsonArray = object.getJSONArray("entidade");
List<String> listaNomes = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonWaether = jsonArray.getJSONObject(i);
//int id = jsonWaether.getInt("ent_id");
String nome = jsonWaether.getString("ent_nome");
listaNomes.add(i, nome);
}
return listaNomes;
}
private String ConsultaServidor() throws IOException {
InputStream is = null;
try {
URL url = new URL(URL_STRING);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
Reader reader = null;
reader = new InputStreamReader(is);
char[] buffer = new char[2048];
reader.read(buffer);
return new String(buffer);
} finally {
if (is != null) {
is.close();
}
}
}
#Override
protected void onPostExecute(List<String> result) {
listener.onConsultaConcluida(result);
super.onPostExecute(result);
}
public interface ConsultaConcluidaListener {
void onConsultaConcluida(List<String> result);
}
}
So you note that I need to implement that interface in the frag. How can I do that?
you have two mistakes in your onCreateView
you are trying to instantiate the AsyncTask after you are returning
you are casting the getActivity() to the interface, without having the Activity implementing it.
it should look like :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
new ConsultaEntidades(this).execute();
return inflater.inflate(R.layout.fragment_entidade, container, false);
}
I am trying to get images from url and set it in a listview through my listviewadapter class. I am getting NULLPOINTEREXCEPTION at openConnection()
in getBitmapFromUrl method at the end.
Here is my code:
ListViewAdapter.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter {
public String msgType[] = new String[8];
public String msgData[] = new String[8];
public String msgTimeStamp[] = new String[8];
Bitmap[] myBitmap = new Bitmap[8];
public Activity context;
int positionX;
URL urlX;
public LayoutInflater inflater;
public ListViewAdapter(Activity context, String[] type, String[] data,
String[] timestamp) {
super();
this.context = context;
this.msgType = type;
this.msgData = data;
this.msgTimeStamp = timestamp;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return msgData.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
ImageView imgView;
TextView txtType;
TextView txtData;
TextView txtTimestamp;
Bitmap myBitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.imgView = (ImageView) convertView.findViewById(R.id.image);
holder.txtType = (TextView) convertView.findViewById(R.id.type);
holder.txtData = (TextView) convertView.findViewById(R.id.data);
holder.txtTimestamp = (TextView) convertView
.findViewById(R.id.timestamp);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// holder.imgView.setImageBitmap(myBitmap[position]);
holder.txtType.setText(msgType[position]);
holder.txtTimestamp.setText(msgTimeStamp[position]);
if (msgType[position].equals("0"))
holder.txtData.setText(msgData[position]);
else {
holder.txtData.setText("");
URL url = null;
try {
url = new URL(msgData[position]);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
urlX=url;
positionX=position;
try {
Thread t = new Thread(new Runnable() {
public void run(){
myBitmap[positionX] = getBitmapFromUrl(urlX);
}
});
t.start();
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
holder.imgView.setImageBitmap(myBitmap[position]);
}
return convertView;
}
public Bitmap getBitmapFromUrl(URL url1) {
Bitmap Bitmap = null;
try {
HttpURLConnection connection = (HttpURLConnection) url1
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return Bitmap;
}
}
EDIT:
Thread t = new Thread(new Runnable() {
public void run(){
myBitmap[positionX] = getBitmapFromUrl(urlX);
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LOGCAT(after edit):
04-03 12:01:26.860: E/AndroidRuntime(11944): FATAL EXCEPTION: Thread-1155
04-03 12:01:26.860: E/AndroidRuntime(11944): java.lang.NullPointerException
04-03 12:01:26.860: E/AndroidRuntime(11944): at com.appquest.flatcassign.ListViewAdapter.getBitmapFromUrl(ListViewAdapter.java:127)
04-03 12:01:26.860: E/AndroidRuntime(11944): at com.appquest.flatcassign.ListViewAdapter$1.run(ListViewAdapter.java:107)
04-03 12:01:26.860: E/AndroidRuntime(11944): at java.lang.Thread.run(Thread.java:856)
Hi I update your base adpter class see blow with implement of the picasso library, you just have to copy and replace the code, sure help you. do not forget to add the jar file.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter {
public String msgType[] = new String[8];
public String msgData[] = new String[8];
public String msgTimeStamp[] = new String[8];
public Activity context;
public LayoutInflater inflater;
public ListViewAdapter(Activity context, String[] type, String[] data,
String[] timestamp) {
super();
this.context = context;
this.msgType = type;
this.msgData = data;
this.msgTimeStamp = timestamp;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return msgData.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
ImageView imgView;
TextView txtType;
TextView txtData;
TextView txtTimestamp;
Bitmap myBitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.imgView = (ImageView) convertView.findViewById(R.id.image);
holder.txtType = (TextView) convertView.findViewById(R.id.type);
holder.txtData = (TextView) convertView.findViewById(R.id.data);
holder.txtTimestamp = (TextView) convertView
.findViewById(R.id.timestamp);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// holder.imgView.setImageBitmap(myBitmap[position]);
holder.txtType.setText(msgType[position]);
holder.txtTimestamp.setText(msgTimeStamp[position]);
if (msgType[position].equals("0"))
holder.txtData.setText(msgData[position]);
else {
holder.txtData.setText("");
Picasso.with(context).load(msgData[position]).into(holder.imgView);
}
return convertView;
}
}
Thank you.
I have a listView in which I bound a column of a table with customCursorAdapter i.e CoordinatorTag like(Home,Office,Factory) etc. from Coordinator Table .but with these tags I also wish to add an extra item in list named ALL at last. how I can do this sir please help me.
thanks
Om Parkash
Check out this .....
I hope this example will helpfull for you
Create /res/layout/row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/listtitle"
android:textSize="22px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/listpubdate"
android:textSize="10px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
now create a class for using a cursor adapter in ListView
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class AndroidRssReader extends ListActivity {
private RSSFeed myRssFeed = null;
public class MyCustomAdapter extends ArrayAdapter<RSSItem> {
public MyCustomAdapter(Context context, int textViewResourceId,
List<RSSItem> list) {
super(context, textViewResourceId, list);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
TextView listTitle=(TextView)row.findViewById(R.id.listtitle);
listTitle.setText(myRssFeed.getList().get(position).getTitle());
TextView listPubdate=(TextView)row.findViewById(R.id.listpubdate);
listPubdate.setText(myRssFeed.getList().get(position).getPubdate());
if (position%2 == 0){
listTitle.setBackgroundColor(0xff101010);
listPubdate.setBackgroundColor(0xff101010);
}
else{
listTitle.setBackgroundColor(0xff080808);
listPubdate.setBackgroundColor(0xff080808);
}
return row;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
URL rssUrl = new URL("http://www.gov.hk/en/about/rss/govhkrss.data.xml");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (myRssFeed!=null)
{
TextView feedTitle = (TextView)findViewById(R.id.feedtitle);
TextView feedDescribtion = (TextView)findViewById(R.id.feeddescribtion);
TextView feedPubdate = (TextView)findViewById(R.id.feedpubdate);
TextView feedLink = (TextView)findViewById(R.id.feedlink);
feedTitle.setText(myRssFeed.getTitle());
feedDescribtion.setText(myRssFeed.getDescription());
feedPubdate.setText(myRssFeed.getPubdate());
feedLink.setText(myRssFeed.getLink());
MyCustomAdapter adapter =
new MyCustomAdapter(this, R.layout.row, myRssFeed.getList());
setListAdapter(adapter);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,ShowDetails.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
bundle.putString("keyDescription", myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position).getLink());
bundle.putString("keyPubdate", myRssFeed.getItem(position).getPubdate());
intent.putExtras(bundle);
startActivity(intent);
}
}
You can use addHeaderView or addFooterView
If the item is at the end of the list, you can use a Footer view for it. use addFooterView(View v, Object data, boolean isSelectable) . Make sure you call this before calling setAdapter() of your listView.
If you want to add an item to your data set, consider using MatrixCursor and its method newRow()
yes you can easily do it using addFooterView.
lv.addFooterView(bottom_layout, null, false);
where lv is listview in which you want to add and bottom_layout is the view or layout you want to add.
Noob android developer trying to create a gallery with thumbnails saved on my server:
I am trying to use my ArrayList in my ImageAdapter so that I can reference my array values when creating my thumbnail list loop. My eclipse package is available for download here since I may not explain this correctly. When I do trying and reference my "thumb" values in my array I am getting an undefined error along with a syntax error when trying to create my "mThumbIds"
I am not sure why I am having such a hard time understanding this.
showThumb.java:
package com.flash_tattoo;
import android.os.Bundle;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class showThumb extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridlayout);
Bundle bundle = getIntent().getExtras();
String jsonData = bundle.getString("jsonData");
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonData);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<image_data> myJSONArray = new ArrayList<image_data>();
for(int i=0;i<jsonArray.length();i++)
{
JSONObject json_data = null;
try {
json_data = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.id = json_data.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.name = json_data.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.thumb = json_data.getString("thumb");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.path = json_data.getString("path");
} catch (JSONException e) {
e.printStackTrace();
}
myJSONArray.add(new image_data());
}
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this,myJSONArray));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(showThumb.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}
ImageAdapter:
package com.flash_tattoo;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
public class ImageAdapter extends ArrayAdapter<image_data>
{
//This code below was put in when I change from BaseAdapter to ArrayAdapter
public ImageAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private Context mContext;
public int getCount() {
return mThumbIds.length;
}
public image_data getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
for(int i=0;i<myJSONArray.lenght();i++){
Object[] myJSONArray;
setImageDrawable(Drawable.createFromPath(myJSONArray[i].thumb)
};
};
}
You have there a private field mThumbIds of type Integer[] and you're trying to initialize it inline, but you fail to do so because you have an static block {} with statements.
I would say you need to just declare:
private Integer[] mThumbIds;
then, in the constructor you can populate the array.