null pointer exception in android? - android

I want my application to look like this.
I am able to get names and types in two different arrays but getting null pointer exception at line marked in the code.names and type array are getting values as I intended.I have double checked my layout files one containing list view and other containing two text view.any help would be greatly appreciable..
package application.test;
import java.util.HashMap;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ListView;
public class TestActivity<types, names> extends ListActivity{
int count[];
int typecount[];
ListView lv;
ListViewAdapterrecent lva;
String[] names;
String[] types;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv=(ListView)findViewById(android.R.id.list);
ContentResolver tcr = getContentResolver();
Cursor tcur=tcr.query(ContactsContract.Data.CONTENT_URI, null, null, null, null);
HashMap<Integer, String> typehashmap=new HashMap<Integer, String>();
HashMap<Integer, String> namehashmap=new HashMap<Integer, String>();
if(tcur.getCount()>0)
{
while(tcur.moveToNext())
{
Boolean temp=false;
String nvalues=tcur.getString(tcur.getColumnIndex(ContactsContract.Data.DATA2));
if (Integer.parseInt(nvalues)==1){
String value="home";
temp=true;
String rw=tcur.getString(tcur.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
int key=Integer.parseInt(rw);
typehashmap.put(key, value);
}
else if(Integer.parseInt(nvalues)==2)
{
String value="mobile";
temp=true;
String rw=tcur.getString(tcur.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
int key=Integer.parseInt(rw);
typehashmap.put(key, value);
}
else
{
String value="work";
temp=true;
String rw=tcur.getString(tcur.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
int key=Integer.parseInt(rw);
typehashmap.put(key, value);
}
if(temp==true)
{
tcur.moveToNext();
String rw=tcur.getString(tcur.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
int key=Integer.parseInt(rw);
String zvalues=tcur.getString(tcur.getColumnIndex(ContactsContract.Data.DATA2));
namehashmap.put(key, zvalues);
}
}//while
tcur.close();
types= typehashmap.values().toArray(new String[typehashmap.size()]);
names= namehashmap.values().toArray(new String[namehashmap.size()]);
lva=new ListViewAdapterrecent(this,names,types);
lv.setAdapter(lva);
}
}
}
listviewrecent.java.............
package application.test;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListViewAdapterrecent extends BaseAdapter{
Activity context;
String[] names;
String[] types;
public ListViewAdapterrecent(Activity context, String[] names, String[] types) {
// TODO Auto-generated constructor stub
this.context=context;
this.names=names;
this.types=types;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return names.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 class viewHolder {
TextView top;
TextView bottom;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
viewHolder holder;
if(convertView==null){
LayoutInflater inflator=context.getLayoutInflater();
convertView=inflator.inflate(R.layout.textviewonly,null);
holder=new viewHolder();
holder.top=(TextView)convertView.findViewById(R.id.toptext);
holder.bottom=(TextView)convertView.findViewById(R.id.bottomtext);
convertView.setTag(holder);
}else{
holder=(viewHolder)convertView.getTag();
}
holder.top.setText(names[position]);
holder.bottom.setText(types[position]);
return convertView;
}
}

just remove the comment from this line
setContentView(R.layout.main);
reason why
because you getting list object from the xml file using its id so you have to first set that layout which contain that control.
updated:
you merge to concept here
You extends the ListActivity and also get the ListView object from the xml file using it's id. Either you can extends the Activity with this code and run it or you can put this lines into the comment and run it.
Lines are:
lv=(ListView)findViewById(android.R.id.list);
and write this way
lv = getListView();
If you extends the ListActivity then you can get the current ListView object like this way or if you want to customize then extends Activity instead of ListActivity
check this http://www.vogella.de/articles/AndroidListView/article.html aritcles

Make sure the variable for lv is not a null. You can try to test if
lv=(ListView)findViewById(android.R.id.list);
is working by ensuring your lv doesn't receive a null.

means that in your main layout , you don't have a listview with id "list"

The edited version is just working fine.I was passing parameters names and types to class listviewadapterrecent before they were actually created thus passing null to the adapter class and getting null values to list view thus getting null pointer exception.

Related

Layout inflater on a custom Dialog fragment return a null pointer exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to show a Dialog fragment with a list of all contacts in there.
I've made this adapter :
package fr.nf.smsplus.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import fr.nf.smsplus.object.Contact;
import fr.nf.smsplus.R;
import fr.nf.smsplus.contactsDialogFragment;
/**
* Created by Nicolas on 22/05/2016.
*/
public class contactListAdapter extends BaseAdapter {
private List<Contact> liste;
private static LayoutInflater inflater = null;
public contactListAdapter(contactsDialogFragment contactsDialogFragment, List<Contact> liste) {
this.liste = liste;
//inflater = (LayoutInflater) contactsDialogFragment.getSystemService(contactsDialogFragment.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return liste.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return liste.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Contact contact = liste.get(position);
View vi = convertView;
if (vi == null)
vi = inflater.inflate(R.layout.item_contact, null);
TextView text = (TextView) vi.findViewById(R.id.contact_name);
text.setText(contact.getDisplayName());
return vi;
}
}
I've made this dialogfragment :
package fr.nf.smsplus;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import java.util.List;
import fr.nf.smsplus.adapter.contactListAdapter;
import fr.nf.smsplus.object.Contact;
/**
* Created by Nicolas on 22/05/2016.
*/
public class contactsDialogFragment extends DialogFragment{
List<Contact> liste;
AbsListView contactList;
public static contactsDialogFragment newInstance(List<Contact> liste){
contactsDialogFragment retour = new contactsDialogFragment();
retour.liste = liste;
return retour;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View contactListView = inflater.inflate(R.layout.dialog_contacts, null);
contactList = (AbsListView) contactListView.findViewById(R.id.listContacts);
contactList.setAdapter(new contactListAdapter(this, liste));
builder.setView(contactListView)
.setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
})
.setTitle(R.string.cdf_title);;
// Create the AlertDialog object and return it
return builder.create();
}
}
I called the dialog like this :
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
contactList = new ArrayList<Contact>();
listContacts();
contactsDialogFragment pickContact = contactsDialogFragment.newInstance(contactList);
pickContact.show(getFragmentManager(), "contacts");
}
});
But i will always have this error :
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup)' on a null object reference at fr.nf.smsplus.adapter.contactListAdapter.getView(contactListAdapter.java:52)
How can i fix this problem ? Is there a problem of execution cycle (trying to inflate a inexisting element)
EDIT
Trying Malik way, i've modified my adapter to add the context, and i got sameerror :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference at fr.nf.smsplus.adapter.contactListAdapter.getView(contactListAdapter.java:55)
I'm trying too this : contactList.setAdapter(new contactListAdapter(getActivity(), liste)); And it will not work ! Just modifying too my adapter constructor to public contactListAdapter(Context context, List<Contact> liste)
Try to inflate the vi View in getView of your adapter like this.
if(vi==null){
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi=inflater.inflate(R.layout.item_contact,parent,false);
}

How to extract all the editText's data from a ListView when one single button (save) is pressed

This is the first question I am posting. Here is my question and below given is the debugged code from android studio.
Here, I have tried to extract the data by taking the data from the adapter into the mainActvity, but I failed as the app is crashing on Clicking the save button. Here the data is nothing but and object.
MainActivity :
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<ListItem_Elements> testsList;
int n=5;//No. of tests
Button btn_save;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
btn_save= (Button)findViewById(R.id.btn_save);
//CustomAdapter adapter;
Resources res=getResources();//Takes the resource permission required to show ListView
testsList= new ArrayList<ListItem_Elements>();
testsList = SetList();
adapter= new CustomAdapter(this, testsList, res);
listView.setAdapter(adapter);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(testsList!=null)
saveValues();
}
});
}
public ArrayList<ListItem_Elements> SetList() {
/*Enter the Test names*/
ArrayList<ListItem_Elements>tests_Array= new ArrayList<ListItem_Elements>();
for(int i=0;i<5;i++) {
ListItem_Elements e = new ListItem_Elements();
e.setTest("XYZ");
e.setResult(null);
tests_Array.add(e);
}
return tests_Array;
}
ArrayList<ListItem_Elements>ar= new ArrayList<>();
public void saveValues() {
if(adapter.extractedArray!=null) {
ar = adapter.extractedArray;
Toast.makeText(MainActivity.this, ar.size(), Toast.LENGTH_SHORT).show();
}
}
}
--------------------------------------------------------------------------------
CustomAdapter :
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Activity activity;
public static ArrayList<ListItem_Elements> extractedArray= new ArrayList<ListItem_Elements>();
private ArrayList<ListItem_Elements> array;
//Declaration of ArrayList which will be used to recieve the ArrayList that has to be putup into the ListView
private LayoutInflater inflater; //To Instantiates a layout XML file into its corresponding View
Resources res;
//protected String bridgeValue;
CustomAdapter(Activity a, ArrayList<ListItem_Elements> b, Resources resLocal) {
activity = a;
array= b;
res = resLocal;
//Initialization of inflater to link the layout of list items
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CustomAdapter() {
}
#Override
public int getCount() {
return array.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
// keeping references for views we use view holder
public static class ViewHolder {
/*Declaration of elements of layout of list items in the class for future use of putting up
data onto the List View*/
TextView textView;
EditText editText;
}
#Override
//Here views were bound to a position
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
// if a view is null(which is for the first item) then create view
if (convertView == null) {
vi = inflater.inflate(R.layout.layout_items, null);
// Taking XML files that define the layout of items, and converting them into View objects.
holder = new ViewHolder();//Stores the elements of the layout of list items
/*Initializing the elements of the layout of list item*/
holder.textView = (TextView) vi.findViewById(R.id.textView);
holder.editText = (EditText) vi.findViewById(R.id.editText);
vi.setTag(holder);
//Stores the view(layout of list item) into vi
}
//else if it already exists, reuse it(for all the next items). Inflate is costly process.
else {
holder = (ViewHolder) vi.getTag();
//Restores the already exisiting view in the 'vi'
}
/*Setting the arrayList data onto the different elements of the layout of list item*/
try {
holder.textView.setText(array.get(position).getTest());
if(holder.editText.getText()!=null) {
ListItem_Elements obj = new ListItem_Elements();
obj.setTest(array.get(position).getTest());
obj.setResult(holder.editText.getText().toString());
extractedArray.add(position, obj);
}
}
catch (Exception e) {
e.getMessage();
}
return vi;//Returns the view stored in vi i.e contents of layout of list items
}
}
--------------------------------------------------------------------------------
public class ListItem_Elements {
String test;
String result;
ListItem_Elements() {
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
You are missing some necessary code. EditText has a method called addTextChangedListener() which accepts a TextWatcher implementation. This implementation would be responsible for updating the data in the adapter.
final ListItem_Elements item = array.get(position);
holder.textView.setText(item.getTest());
holder.editText.setText(item.getResult());
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
item.setResult(s.toString());
}
// omitted empty impls for beforeTextChanged() and afterTextChanged(), you need to add them
});
Now, everytime the user updates the EditText, your adapter value will be updated. Then you just get the array values:
public void saveValues() {
// testLists in the activity and array in the adapter are references
// to the same list. So testLists already has the updated results
}
And take out this whole block of code:
holder.textView.setText(array.get(position).getTest());
if(holder.editText.getText()!=null) {
ListItem_Elements obj = new ListItem_Elements();
obj.setTest(array.get(position).getTest());
obj.setResult(holder.editText.getText().toString());
extractedArray.add(position, obj);
}
It doesn't do the right thing.
you are filling the listView with value from an ArrayList. Why you don't just get values from the your ArrayList ??
public void saveValues() {
if(tests_Array!=null) {
//and here you get values from your list
//by a simple for instruction
Toast.makeText(MainActivity.this, tests_Array.size(), Toast.LENGTH_SHORT).show();
}
}

How to save and retrieve values from editText different for each listView row?

I have created a listView activity which opens dialog boxes on item click. In the dialog box, the users can enter different values, in an editText, which are saved in a textView, in the same list view item. That's working perfect, the problem is that if I close the application, when I open it again, the values saved, aren't there anymore. How to keep the value after closing the application?
I tried working with SharedPrefences, but the problem was that values are different for each row in the listView, so just sharing the TextView wasn't working. Then I tried something else, but for a week I got stuck into many NullPointerExceptins and I couldn't have done nothing so far on that way.
Here is my:
Adapter - NoteAdapater.java:
package com.cngcnasaud.orar;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class NoteAdapter extends BaseAdapter {
String[] result;
Context context;
private static LayoutInflater inflater = null;
private Dialog dialog;
public NoteAdapter(Note note, String[] prgmNameList, String[] saved) {
// TODO Auto-generated constructor stub
result = prgmNameList;
context = note;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return result.length;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
public TextView text;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.note_items, null);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.text = (TextView) rowView.findViewById(R.id.textView2);
holder.tv.setText(result[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Materie:" + result[position]);
final EditText txtMode = (EditText) dialog
.findViewById(R.id.dialog);
Button btnSave = (Button) dialog.findViewById(R.id.bsave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = txtMode.getText().toString();
holder.text.setText(data);
dialog.dismiss();
Log.d("data", data);
}
});
dialog.show();
}
});
return rowView;
}
}
And constructor - Note.java:
package com.cngcnasaud.orar;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
public class Note extends Activity {
public static final ListAdapter NoteAdapter = null;
ListView lv;
Context context;
ArrayList<?> prgmName;
public static String[] prgmNameList = { "Romana - ", "Matematica - ",
"Lb. Engleza - ", "Lb. Germana/Franceza - ", "Istorie - ",
"Geografie - ", "Biologie - ", "Fizica - ", "Ed. Fizica - " };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_listview);
context = this;
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You are loosing the data because your data is static, you have define it in
prgmNameList = { "Romana - ", "Matematica - ",
"Lb. Engleza - ", "Lb. Germana/Franceza - ", "Istorie - ",
"Geografie - ", "Biologie - ", "Fizica - ", "Ed. Fizica - " };
Every time you close the app it will pick that data. In order to save the changes you need to implement a form of storage. Check the Android training page: Saving Data
I think the best option is to make a database Saving Data in SQL Databases
Use SQLite datbase for storing the data,It is static database kept all the values until uninstallation of the app.
Another way is use some online database using web-service.
For example RESTFUL webservice

load a few json elements at a time by scrollview

I have a ListFragment that contains a list of items. I would like to load say 9 items at a time and when i scroll and reach the bottom of the listview i want to load another 9 items in background.
I make 2 request to my web server:
1) to get all the item id's of the items, by a searh() method
2) to get all the item details of a specific item though its id, by getId(id) method
The version i have implemented gets all the ids and then loads all the items at once in the doInBackground method of AsyncTask and it works. and it takes very long (i dont want a button because its really ugly).
I'd like to introduce this thing about the onScrollListener so that when i first open my app, in background i get all the ids, and then i get the first 9 items and show them. then when i scroll to the end i want to load the next 9 items. How do i do this?
I have read a few posts but it not clear to me, especially due to the fact that i have 2 functions that need to be run in background, 1 function needs to be run once while the other many times and i need to keep track of which id's i getting.
I would also if possible like to add the function that if i pull the ListView a little then it should update my view.
Here is my code:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.adapter.ListViewAdapter;
import com.prjma.lovertech.util.MVPFunctions;
public class CompraFragment extends ListFragment {
public ListView listView;
public ListViewAdapter adapter;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private DownloadTask mDownloadTask = null;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_compra, false);
View rootView = inflater.inflate(R.layout.fragment_compra, container, false);
// now you must initialize your list view
listView = (ListView) rootView.findViewById(android.R.id.list);
mDownloadTask = new DownloadTask();
mDownloadTask.execute((Void) null);
return rootView;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog progressDialog;
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
//Here i get all the id's
ArrayList<Long> ids = MVPFunctions.getMioSingolo().search();
//for each id get all its details and put it in a map
items = new ArrayList<HashMap<String, Object>>();
for(int i=0; i < ids.size(); i++){
items.add(MVPFunctions.getMioSingolo().getItem(ids.get(i)));
}
return true;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(getActivity(), "", "Downloading Content...");
}
#Override
protected void onPostExecute(final Boolean success) {
mDownloadTask = null;
// dismiss the dialog after getting all products
progressDialog.dismiss();
//showProgress(false);
if (items.get(0).get("status error")!= null){
Toast.makeText(getActivity(), "status error = " + items.get(0).get("status error"), Toast.LENGTH_LONG).show();
Log.i("status error put toast", (String) items.get(0).get("status error"));
//fai qualcosa, tipo torna indietro, ecc
}
// updating UI from Background Thread
ListViewAdapter adapter = new ListViewAdapter(getActivity(),R.layout.listview_item_row, items, icon);
// updating listview
listView.setAdapter(adapter);
}
#Override
protected void onCancelled() {
mDownloadTask = null;
//showProgress(false);
}
}
}
Adapter class:
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.activity.DettagliActivity;
import com.prjma.lovertech.model.Item;
public class ListViewAdapter extends ArrayAdapter<String> {
private static LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
//public ImageLoader imageLoader;
public ListViewAdapter(Context context, int listviewItemRow, ArrayList<HashMap<String, Object>> items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder viewHolder = new ViewHolder();
if (row == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.listview_item_row, null);
viewHolder.ic_thumbnail = (ImageView)row.findViewById(R.id.ic_thumbnail);
viewHolder.scadenza = (TextView)row.findViewById(R.id.tvScadenza);
viewHolder.prezzo = (TextView)row.findViewById(R.id.tvPrezzo);
viewHolder.followers = (TextView)row.findViewById(R.id.tvFollowers);
viewHolder.hProgressBar = (ProgressBar)row.findViewById(R.id.hProgressBar);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)row.getTag();
}
HashMap<String, Object> item = items.get(position);
viewHolder.ic_thumbnail.setImageBitmap((Bitmap) item.get("pic1m"));
viewHolder.scadenza.setText((CharSequence) item.get("scadenza"));
viewHolder.prezzo.setText((CharSequence) item.get("prezzo"));
viewHolder.followers.setText((CharSequence) item.get("followers"));
viewHolder.hProgressBar.setProgress((Integer) item.get("coefficient"));
//row.onListItemClick(new OnItemClickListener1());
row.setOnClickListener(new OnItemClickListener(position));
return row;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
static class ViewHolder {
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
}
}
In your adapter, check how close the user is from the bottom of the data set. When they get to the end, call a method that fetches more items from the network. I normally use a "REFRESH_THRESHOLD" integer to prefetch items before they're needed.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Item current = getItem(position);
//Pre-fetch
if(getCount() - position <= REFRESH_THRESHOLD){
//If there are more items to fetch, and a network request isn't already underway
if(is_loading == false && has_remaining_items == true){
getItemsFromNetwork();
}
}

How to add data from db.selectAll Please check it agian

Now i try to use adapter . But i dont understand how to set value from data .Becuase in friends = db.selectall ,value in friend have 3 value(fname,lname,nickname).So my question is How to set value(fname/lname/nickname OR one or the other) My code NOW look like this ::::
package com.example.sqlite;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sqlite.db.FriendsDB;
import com.example.sqlite.entry.FriendEntry;
public class FriendsListActivity extends Activity {
private Context context;
private FriendsDB db;
private ArrayList<FriendEntry> friends;
private ArrayList<String> data;
private TextView hellotext;
private ListView hellolistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.friendlist_layout);
}
public void showAllList(){
//view matching
hellotext = (TextView) findViewById(R.id.hellotext);
hellolistview = (ListView) findViewById(R.id.hellolistview);
//select data
friends = db.selectAll();
if(friends.size()==0){
Toast.makeText(context,"You dont have any friend.",Toast.LENGTH_SHORT).show();
}else{
data = new ArrayList<String>();
for (int i = 1;i<=friends.size();i++){
// set value for data
**data.add("Your Name is "+friends["fname"]);<< I want to add data like this .How to correct**
}
}
}
private class adapter extends BaseAdapter{
private Holder holder;
#Override
//ดาต้ามีกี่แถว
public int getCount() {
// TODO Auto-generated method stub
return friends.size();
}
#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;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
//create
if( view == null){
view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_layout,null);
holder = new Holder();
holder.title = (TextView) view.findViewById(R.id.item_title);
view.setTag(holder);
}else{
holder = (Holder) view.getTag();
}
//assign data / wait for data
return null;
}
private class Holder{
//view แต่ละตัวเก็บค่าอะไรบ้าง
public TextView title;
}
}
}
When you have data in Cursor and you want to display it in a ListView, you need to use a CursorAdapter.
You can either use the pre-defined SimpleCursorAdapter or if you want custom views, you can extend the CursorAdapter class.
Tutorial here: http://thinkandroid.wordpress.com/2010/01/11/custom-cursoradapters/
You are doing it allmost all right , but I suggest you to use an ArrayList of HashMap type instead of using Friends class.
This will lower your application burden.
ArrayList<HashMap<Object,String>> list=new ArrayList<HashMap<Object,String>>();
HashMap<Object,String> hm;
in your select all method
do{
hm=new HashMap<Object,String>();
hm.add(Key_Name,"retrieve the value from cursor here");
list.add(hm);
}while(c.movetonect());
return list;
in your activity
ArrayList<HashMap<Object,String>> list=new ArrayList<HashMap<Object,String>>();
list=db.selectAll();
HashMap<Object,String> hm;
for (int i=0;i<list.length;i++){
hm=list.getIndex(i); //retrieve all the vaalues here
}
use list adapters which accept list to populate the listview

Categories

Resources