The title of this question is same but technical issue are different.
Hi i am trying to get data from SQLite but i am able to show only last item in listview. I tried different- different solution but not getting success.
Problem is not getting item from SQLite(I am able to fetch all item) but showing item using adapter in listview.
Here is my code.
ListActivity.java
db=new DBHelper(getBaseContext());
db.getWritableDatabase();
try {
final DBHelper m = new DBHelper(getBaseContext());
final List<GetSet> NotesWiseProfile = m.getBabyDetails();
for (final GetSet cn : NotesWiseProfile) {
counter++;
String babyName = cn.getBabyName();
String babyImage = cn.getBabyImage();
int babyId = cn.getBabyId();
BabyData baby_data[] = new BabyData[]
{
new BabyData(R.drawable.ic_launcher, babyName,babyId),
};
adapter = new MobileArrayAdapter(this,
R.layout.list_row, baby_data);
listView1.invalidateViews();
listView1.setAdapter(adapter);
}
}
catch (Exception e) {
}
BabyData.java
public class BabyData {
public int icon;
public String title;
public int babyid;
public BabyData(){
super();
}
public BabyData(int icon, String title,int babyId) {
super();
this.icon = icon;
this.title = title;
babyid = babyId;
}
}
MobileArrayAdapter.java
public class MobileArrayAdapter extends ArrayAdapter<BabyData>{
Context context;
int layoutResourceId;
BabyData data[] = null;
public MobileArrayAdapter(Context context, int layoutResourceId, BabyData[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
DataHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new DataHolder ();
holder.imgIcon = (ImageView)row.findViewById(R.id.imvBabyFace);
holder.txtTitle = (TextView)row.findViewById(R.id.tvbabyNameList);
holder.txtBabyId = (TextView)row.findViewById(R.id.tvBabyId);
row.setTag(holder);
}
else
{
holder = (DataHolder )row.getTag();
}
BabyData weather = data[position];
holder.txtTitle.setText(weather.title);
holder.txtBabyId.setText(String.valueOf(weather.babyid));
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class DataHolder
{
ImageView imgIcon;
TextView txtTitle;
TextView txtBabyId;
}
}
I don't understand what's wrong in my code. Please give me any hint or reference.
Thanks in Advance.
Put the listview declarations out of the for loop, something like:
BabyData baby_data[] = new BabyData[NotesWiseProfile.size()];
for (final GetSet cn : NotesWiseProfile) {
String babyName = cn.getBabyName();
String babyImage = cn.getBabyImage();
int babyId = cn.getBabyId();
baby_data[counter] = new BabyData(R.drawable.ic_launcher, babyName,babyId);
counter++;
}
adapter = new MobileArrayAdapter(this,
R.layout.list_row, baby_data);
listView1.invalidateViews();
listView1.setAdapter(adapter);
I think you should use a field for storing you babies. Currrently, you are using a local Baby array for that. As far as I know, the ListView always gets its data from the array you passed to it (invalidating it causes the ListView to look up that data again.
To recap: Store your array as a field - if data changes, update the array and call notifyDatasetChanged() on your adapter, which will cause your ListView to reload the data.
Related
I need to be able to choose or pick an item from a list and after I choose it, the name of that item will go into one field and the corresponding weight to that item will go into another field.
I've been really stuck on this. I tired making a adapter but it wasn't working out and I'm just so lost, I don't know where to go with it.
I would really appreciate help.
If you need any code that I've done please say and I'll put it up straight away.
I don't have a database, I have a class of an array or numbers and Letter.
Thanks all!
Main.java
public void Chem() {
Chemical chemical_data[] = new Chemical[]
{
new Chemical("Acid", 125.33),
new Chemical("Blue", 145.3356),
};
ChemicalAdapter adapter = new ChemicalAdapter(this, R.layout.sollayout, chemical_data);
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
weightval = (EditText) findViewById(R.id.editText);
//ChemicalAdapter header = new ChemicalAdapter(this, R.layout.sollayout, null);
//weightval.addHeaderView(header);
chemname.setAdapter(adapter);
}
public void Chemname()
{
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
AutoCompleteTextView b = (AutoCompleteTextView) findViewById(R.id.editText4);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Chem();
}
});
}
Chemical.java
public class Chemical {
String chemicalValue;
double weight;
public Chemical(String chemicalValue, double weight) {
this.chemicalValue = chemicalValue;
this.weight = weight;
}
public String getChemicalValue() {
return chemicalValue;
}
public double getWeight() {
return weight;
}
}
ChemicalAdpater.java
public class ChemicalAdapter extends ArrayAdapter<Chemical> {
Context context;
int layoutResourceId;
Chemical data[] = null;
public ChemicalAdapter(Context context, int layoutResourceId, Chemical[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChemicalHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChemicalHolder();
holder.chemname = (AutoCompleteTextView)row.findViewById(R.id.editText4);
holder.weightval = (EditText)row.findViewById(R.id.editText);
row.setTag(holder);
}
else
{
holder = (ChemicalHolder)row.getTag();
}
Chemical chemical = data[position];
holder.weightval.setText(String.valueOf(chemical.weight));
holder.chemname.setText(chemical.chemicalValue);
return row;
}
static class ChemicalHolder
{
AutoCompleteTextView chemname;
EditText weightval;
}
}
I am trying to update the contents of my ArrayAdapter. I have tried calling the method notifyDataSetChanged() on the adapter and invalidate() on the ListView but I do not see the data within the adapter being changed. I spent two hours searching through every StackOverflow post about this topic, but none of the answers worked.
Here is the ArrayAdapter class which I extended
public class ChannelAdapter extends ArrayAdapter<ChannelRow> {
Context context;
int layoutResourceId;
ChannelRow[] data;
public ChannelAdapter(Context context, int layoutResourceId, ChannelRow[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChannelRowHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChannelRowHolder();
holder.userName = (TextView)row.findViewById(R.id.userNameTextView);
holder.channelName = (TextView)row.findViewById(R.id.channelNameTextView);
row.setTag(holder);
}
else
{
holder = (ChannelRowHolder)row.getTag();
}
ChannelRow channelRow = data[position];
holder.userName.setText(channelRow.getUserName());
holder.channelName.setText(channelRow.getChannelName());
return row;
}
static class ChannelRowHolder
{
TextView userName;
TextView channelName;
}
}
Below is my Activity which I deal with the adapter.
public class ChannelNameActivity extends Activity {
private ListView channelListView ;
private ChannelRow[] channelData;
private ChannelAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
this.setContentView(R.layout.activity_channelname);
// create ListView of channels
grabSessions();
channelData = new ChannelRow[]{ // default data
new ChannelRow("user1", "channel1"),
new ChannelRow("user2", "channel2")
};
// attach ListView adapters/views
adapter = new ChannelAdapter(this, R.layout.channel_row, channelData);
channelListView = (ListView) findViewById(R.id.channelListView);
final View contentView = (View)getLayoutInflater().inflate(R.layout.activity_channelname, null);
channelListView.addHeaderView(contentView);
channelListView.setAdapter(adapter);
....
}
private void grabSessions() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Session");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
createSessionsList((ArrayList<ParseObject>) objects);
} else {
// error with query
}
}
});
}
/**
* Called from grabSessions()
* Initializes channelData with the queried ParseObject Sessions
* #param objects the queried Sessions
*/
private void createSessionsList(ArrayList<ParseObject> objects){
ArrayList<ChannelRow> channels = new ArrayList<>();
ChannelRow newRow = null;
for (ParseObject o : objects){
newRow = new ChannelRow((String)o.get("hostName"), (String)o.get("chatTitle"));
channels.add(newRow);
}
channelData = channels.toArray(new ChannelRow[channels.size()]);
adapter.notifyDataSetChanged();
channelListView.invalidate();
}
}
Sir;
check this out private ChannelRow[] channelData; that's your instance variable, you instantiate it in your onCreate() this way
channelData = new ChannelRow[]{ // default data
new ChannelRow("user1", "channel1"),
new ChannelRow("user2", "channel2")
}; // channelData is holding is reference to the object being created with the `new` keyword
so for example if you add one more object to channelData and call your notifyDataSetChanged() it will refresh but in your createSessionsList(ArrayList<ParseObject> objects) method you assign your channelData to a new object like this channelData = channels.toArray(new ChannelRow[channels.size()]); and this reference is not what the ListView's Adapter data is pointing to, so your notifyDataSetChanged() does not work because it has not changed. what you have to do is recall the instantiation line, this is the complete code
private void createSessionsList(ArrayList<ParseObject> objects){
ArrayList<ChannelRow> channels = new ArrayList<>();
ChannelRow newRow = null;
for (ParseObject o : objects){
newRow = new ChannelRow((String)o.get("hostName"), (String)o.get("chatTitle"));
channels.add(newRow);
}
channelData = channels.toArray(new ChannelRow[channels.size()]);
adapter = new ChannelAdapter(this, R.layout.channel_row, channelData);
//edit started here
// set your Listview to the adapter
channelListView.setAdapter(adapter); // you set your list to the new adapter
adapter.notifyDataSetChanged();// you can remove it if you like
}
EDIT 1
if you hate the idea of calling this line adapter = new ChannelAdapter(this, R.layout.channel_row, channelData); all the time i'd suggest you use ArrayList and use the ArrayList.add(Object o) function to update your item then you can all notifyDataSetChanged() ..
Hope it helps..
I have a custom array adapter for a ListView. The goal is to have each list item have an individual picture, and that when the user clicks on the item they are taken to a web page. I have the image part working, and there are some stackoverflow answers for where to put the onItemClickListener. It seems it would go in the custom array adapter class But I can't figure out how to access the url from the list item.
Here is the code:
public class Animal
{
int image_resource_id;
String animal_type;
String wikipedia_url;
Animal(int image_resource_id, String animal_type, String wikipedia_url)
{
this.image_resource_id = image_resource_id;
this.animal_type = animal_type;
this.wikipedia_url = wikipedia_url;
}
}
class AnimalViewHolder
{
ImageView animal_image = null;
TextView animal_name = null;
String animal_url = "";
}
class CustomAnimalAdapter extends ArrayAdapter<Animal>
{
Context context;
int layoutResourceId;
Animal data[] = null;
public CustomAnimalAdapter(Context context, int layoutResourceId, Animal[] data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
AnimalViewHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new AnimalViewHolder();
holder.animal_image = (ImageView)row.findViewById(R.id.animal_image);
holder.animal_name = (TextView)row.findViewById(R.id.animal_name);
row.setTag(holder);
}
else
{
holder = (AnimalViewHolder)row.getTag();
}
Animal animal = data[position];
holder.animal_name.setText(animal.animal_type);
holder.animal_image.setImageResource(animal.image_resource_id);
return row;
}
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Animal[] animal_list = {
new Animal(R.drawable.lion, "Lion", "http://en.wikipedia.org/wiki/Lion"),
new Animal(R.drawable.tiger, "Tiger", "http://en.wikipedia.org/wiki/Tiger"),
new Animal(R.drawable.bear, "Bear", "http://en.wikipedia.org/wiki/Bear"),
new Animal(R.drawable.monkey, "Monkey", "http://en.wikipedia.org/wiki/Monkey"),
new Animal(R.drawable.moose, "Moose", "http://en.wikipedia.org/wiki/Moose"),
new Animal(R.drawable.shark, "Shark", "http://en.wikipedia.org/wiki/Shark")
};
CustomAnimalAdapter adapter = new CustomAnimalAdapter(this,
R.layout.row_item, animal_list);
list_view_1 = (ListView)findViewById(R.id.listView1);
list_view_1.setAdapter(adapter);
}
update your adapter getview with
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(animal.wikipedia_url));
context.startActivity(browserIntent);
}
});
I have a class that looks like this:
public class Vizita {
public int icon;
public String titlu;
public String loc;
public String idviz;
public Vizita(){
super();
}
public Vizita(int icon, String titlu, String loc, String idviz) {
super();
this.icon = icon;
this.titlu = titlu;
this.loc = loc;
this.idviz = idviz;
}
}
I use AsyncTask to retrieve a JSON array from a PHP. All works perfect for simple layout of listview. But I want to use a more complex layout, so I designed one that uses all 4 values from Vizita.class above. But I do not know how to set the adapter for it, because the way I try it, gives me errors.
Of course I am trying to do it in onPostExecute, like this:
public class MyActivity extends Activity {
{...}
JSONArray lststat;
{...}
public JSONArray liststatus() {
JSONArray jdata=post.getserverdataX(url_connectX);
return jdata;
}
class asyncpost extends AsyncTask< String, String, String > {
Vizita weather_data[];
....
protected void onPostExecute(String result) {
VizitaAdapter adapter = new VizitaAdapter(MyActivity.this,R.layout.listview_item_row, weather_data);
myListView.setAdapter(adapter);
...}
And in doInBackground I am processing the JSON like this:
lststat = liststatus();
JSONObject json_data;
try {
int length = lststat.length();
Vizita weather_data[] = new Vizita[length];
for (int i = 0; i < length; i++)
{
json_data = lststat.getJSONObject(i);
weather_data[i].titlu =json_data.getString("clientnume");
weather_data[i].idviz =json_data.getString("idvizite");
weather_data[i].loc =json_data.getString("localitate");
}
} catch (Exception e) {
Log.e(null, e.toString());
}
where liststatus() is where I call the asyncTask to retrieve the needed JSONArray.
But I receive a java.lang.NullPointerException in the for loop (if I comment the setAdapter line).
I assume I did not initialize the weather_data array properly ?!?!?
If I (uncomment) set the adapter in onPostExecute I receive a crash error "Force close"
I do not receive any errors in the IDE, seeming that the syntaxes are fine.
Please tell me what am I doing wrong? And how can I fix it?
The code for the VizitaAdapter is bellow
public class VizitaAdapter extends ArrayAdapter<Vizita>{
Context context;
int layoutResourceId;
Vizita data[] = null;
public VizitaAdapter(Context context, int layoutResourceId, Vizita[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.txtLoco = (TextView)row.findViewById(R.id.txtLocalitate);
holder.txtIdviz = (TextView)row.findViewById(R.id.txtIdVizite);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Vizita weather = data[position];
holder.txtTitle.setText(weather.titlu);
holder.txtLoco.setText(weather.loc);
holder.txtIdviz.setText(weather.idviz);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
TextView txtLoco;
TextView txtIdviz;
}
}
Probably you forgot initialize Vizita object in loop:
json_data = lststat.getJSONObject(i);
weather_data[i] = new Vizita();
weather_data[i].titlu =json_data.getString("clientnume");
weather_data[i].idviz =json_data.getString("idvizite");
weather_data[i].loc =json_data.getString("localitate");
I am trying to set the data to an adapter through an AsyncTask. This has caused alot of grief - Most recently when trying to set the Array Adapter.
The following method is called onPostExecute();
private void setQueues(final JSONObject[] qInfo)
{
queues = new QueueItem[qInfo.length];
for(int i = 0; i < qInfo.length; i++)
{
queues[i] = new QueueItem();
//final int ii = i;
// Formatting the queue title
String name = qInfo[i].optString("name").replace("-", " ");
queues[i].label = name;
try {
if(qInfo[i].getString("active").contains("1"))
{
queues[i].value = true;
}
else
{
queues[i].value = false;
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
lv.setAdapter(new QueueAdapter(getActivity(),
R.layout.queues_items, queues));
This causes the following exception runtime : link here
EDIT : As requested, here is QueueAdapter :
public class QueueAdapter extends ArrayAdapter<QueueItem>{
Context context;
int layoutResourceId;
QueueItem data[] = null;
public QueueAdapter(Context context, int layoutResourceId, QueueItem[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
QueueHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new QueueHolder();
holder.queueswitch = (Switch)row.findViewById(R.id.queues_item_switch);
holder.txtLabel = (TextView)row.findViewById(R.id.queues_item_text);
row.setTag(holder);
}
else
{
holder = (QueueHolder)row.getTag();
}
QueueItem queue = data[position];
holder.txtLabel.setText(queue.label);
holder.queueswitch.setChecked(queue.value);
return row;
}
static class QueueHolder
{
Switch queueswitch;
TextView txtLabel;
}
}
lv.setAdapter(new QueueAdapter(getActivity(),
R.layout.queues_items, queues));
this snippet should be in try block.. Because If there is JSONException all elements in that array will be null...
I mean to say.. put for loop inside try block and not the oppt.. if you still want to loop when an Exception occurs.. Then Try using Collections instead of array..