How can i get image from image url in image view.
My imageUrl is coming from databaseadapter.
In Fields class LocationImage dataype is string but in setBackgroundResource method it is asking for int value as parameter. LocationImage url is getting from database, so that i've taken that as string variable.
code lines are here.
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FindPlaces extends ListActivity{
private SQLiteDatabase DbLoc;
ListView lv;
int val;
private ArrayList<Fields> results = new ArrayList<Fields>();
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.places);
getallLocs();
setListAdapter(new StudentListAdapter(this, val, results));
}
class StudentListAdapter extends ArrayAdapter<Fields>{
private ArrayList<Fields> locationDetails;
private Context mContext;
public StudentListAdapter(Context context,int textViewResourceId, ArrayList<Fields> results) {
super(context, textViewResourceId, results);
// TODO Auto-generated constructor stub
System.out.println("Constructor StudentList Adapter...");
this.locationDetails = results;
mContext = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return results.size();
}
#Override
public Fields getItem(int position) {
// TODO Auto-generated method stub
return locationDetails.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(v == null){
LayoutInflater vl = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vl.inflate(R.layout.placeslist, null);
}
Fields o = results.get(position);
if (o != null) {
TextView iv = (TextView)v.findViewById(R.id.toptext);
TextView tv_sNo = (TextView)v.findViewById(R.id.toptext1);
ImageView tv_Image = (ImageView)v.findViewById(R.id.Locimage);
iv.setText(o.getLocationName());
//tv_sNo.setText("Status: "+ o.getOrderStatus());
tv_sNo.setText(o.getLocationImage());
tv_Image.setBackgroundResource(o.getLocationImage());
}
DbLoc.close();
return v;
}
}
static class ViewHolder
{
TextView Locationname;
ImageView Locationimage;
}
private void getallLocs() {
// TODO Auto-generated method stub
try {
DatabaseHelper dbHelper = new DatabaseHelper(
this.getApplicationContext());
DbLoc = dbHelper.getWritableDatabase();
Cursor c = DbLoc.rawQuery("SELECT " + DatabaseHelper.LocationName+ " , " + DatabaseHelper.LocationImage + " FROM "
+ DatabaseHelper.LOCATIONTABLE , null);
System.out.println("SELECT " + DatabaseHelper.LocationLang+" , "+DatabaseHelper.LocationLat+" , "+ DatabaseHelper.LocationName
+ " ," + DatabaseHelper.LocationImage + " FROM "
+ DatabaseHelper.LOCATIONTABLE );
if (c != null) {
if (c.moveToFirst()) {
do {
String LocationName= c.getString(c.getColumnIndex("LocationName"));
String Mobile = c.getString(c
.getColumnIndex("LocationImage"));
Fields p = new Fields(LocationName, Mobile);
results.add(p);
} while (c.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
}
}
}
if u got image url use the below code to set the image from url to imageview
Bitmap mbmp = BitmapFactory.decodeStream(new java.net.URL("urlname").openStream());
Imageview_ref.setImageBitmap(mbmp);
Related
I had created a custom list view. Please tell me how to delete a entry from listview. I don't know where to write a code for delete button in my code. Please help me. Thanks..
Here is ListAdapater.java class:
package com.example.login;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ListAdapater extends ArrayAdapter<String> {
customButtonListener customListner;
public interface customButtonListener {
public void onButtonClickListner(int position, String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
private ArrayList<String> data = new ArrayList<String>();
public ListAdapater(Context context, ArrayList<String> dataItem) {
super(context, R.layout.my_custom_list_layout, dataItem);
this.data = dataItem;
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.my_custom_list_layout, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.TextView);
viewHolder.button = (Button) convertView.findViewById(R.id.delete);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String temp = getItem(position);
viewHolder.text.setText(temp);
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position, temp);
}
}
});
return convertView;
}
public class ViewHolder {
TextView text;
Button button;
}
}
Hompage.java class:
package com.example.login;
import com.example.login.ListAdapater.customButtonListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Hompage extends Activity implements customButtonListener {
ListView listView;
ListAdapater adapter;
ArrayList<String> dataItems = new ArrayList<String>();
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
db = openOrCreateDatabase("login", MODE_PRIVATE, null);
// My code
String query1 = "SELECT * FROM USERS;";
int c = 0;
try {
Cursor c1 = db.rawQuery(query1, null);
if (c1.moveToFirst()) {
String[] temp2 = new String[c1.getCount()];
do {
String tempo = "Name" + ": " + c1.getString(1) + " " + c1.getString(2) + " \n" + "Gender" + ": "
+ c1.getString(4) + "\n " + "Hobbies" + ": " + c1.getString(8) + " \n" + "User Type" + ": "
+ c1.getString(9);
temp2[c] = tempo;
c++;
// String[] dataArray = temp2;
// List<String> datatemp = Arrays.asList(dataArray);
// dataItems.addAll(datatemp);
} while (c1.moveToNext());
String[] dataArray = temp2;
List<String> datatemp = Arrays.asList(dataArray);
dataItems.addAll(datatemp);
listView = (ListView) findViewById(R.id.listView);
adapter = new ListAdapater(Hompage.this, dataItems);
adapter.setCustomButtonListner(Hompage.this);
listView.setAdapter(adapter);
}
} catch (Exception e) {
}
}
#Override
public void onButtonClickListner(int position, String value) {
//EDITED CODE...
// TODO Auto-generated method stub
String query = "SELECT USER_TYPE FROM USERS WHERE userName = '" + temp + "'";
Cursor c2 = db.rawQuery(query, null);
if (c2.moveToFirst()) {
if (c2.getString(0).equals("Admin")) {
dataItems.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_LONG).show();
return;
}
else{
Toast.makeText(getApplicationContext(), "Only Admin can delete", Toast.LENGTH_LONG).show();
}
}
}
}
Try like this
#Override
public void onButtonClickListner(int position, String value) {
// TODO Auto-generated method stub
dataItems.remove(position);
adapter.notifyDataSetChanged();
// call this method
deleteRowFromTable(your_table_name, your_column_name, value)
}
public void deleteRowFromTable(String tableName, String columnName, String keyValue) {
String whereClause = columnName + "=?";
String[] whereArgs = new String[]{String.valueOf(keyValue)};
yourDatabase.delete(tableName, whereClause, whereArgs);
}
I have listviewadapter , it contains some fields like : status, notes, salesname, insertdate (txtTgglInsert), image. I want to do sorting based insertdate(txtTgglInsert) descending(based on recent status). How could I do this one on my programm with calling this adapter?
my adapter :
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ListViewTimelineAdapter extends BaseAdapter{
private static ArrayList<URLPostClass> DataProcessorResult;
private LayoutInflater myInflater;
Context mycontext;
public ListViewTimelineAdapter(Context context, ArrayList<URLPostClass> results) {
DataProcessorResult = results;
myInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//Log.d("count", String.valueOf(DataProcessorResult.size()));
return DataProcessorResult.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return DataProcessorResult.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
final Context mycontext=parent.getContext();
if(convertView == null) {
convertView = myInflater.inflate(R.layout.custom_viewtimeline, null);
holder = new ViewHolder();
holder.txtJenisStatus = (TextView) convertView.findViewById(R.id.jenisstatus);
holder.txtStatus = (TextView) convertView.findViewById(R.id.status);
holder.txtSales = (TextView) convertView.findViewById(R.id.sales);
holder.txtTgglInsert = (TextView) convertView.findViewById(R.id.tgglinsert);
holder.imgPosting= (ImageView) convertView.findViewById(R.id.imgposting);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtJenisStatus.setText(DataProcessorResult.get(position).getJenisStatus());
holder.txtStatus.setText(DataProcessorResult.get(position).getRemark());
holder.txtSales.setText(DataProcessorResult.get(position).getNamaSales());
holder.txtTgglInsert.setText(DataProcessorResult.get(position).getTgglInsert());
holder.txtStatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
holder.txtJenisStatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbllistviewitem));
holder.txtSales.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbllistviewitem));
holder.txtTgglInsert.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbllistviewitem));
try {
String image_url = DataProcessorResult.get(position).getPath();
if (image_url.length()>0) {
ImageLoader imgLoader = new ImageLoader(mycontext);
imgLoader.DisplayImage(image_url, 0, holder.imgPosting);
holder.imgPosting.getLayoutParams().width= mycontext.getResources().getDimensionPixelSize( R.dimen.photolistviewitem);
holder.imgPosting.getLayoutParams().height= mycontext.getResources().getDimensionPixelSize( R.dimen.photolistviewitem);
}else {
holder.imgPosting.setVisibility(View.GONE);
}
} catch (Exception e) {
// TODO Auto-generated catch block
//Toast.makeText(mycontext, e.toString(), Toast.LENGTH_SHORT).show();
}
//if (position % 2 == 1) {convertView.setBackgroundColor(Color.WHITE);} else {convertView.setBackgroundColor(Color.rgb(208,212,208)); }
return convertView;
}
static class ViewHolder {
TextView txtJenisStatus;
TextView txtStatus;
TextView txtSales;
TextView txtTgglInsert;
ImageView imgPosting;
}
}
Since your Adapter is based on an ArrayList of objects, you can change your implementation to subclass ArrayAdapter (Docs: http://developer.android.com/reference/android/widget/ArrayAdapter.html)
public class ListViewTimelineAdapter extends ArrayAdapter<URLPostClass> {
after that, sorting would be trivial:
ArrayList<URLPostClass> myListData = ...
ArrayAdapter<URLPostClass> adapter = new MyArrayAdapter<URLPostClass>(context, R.layout.my_layout, myListData);
adapter.sort(new Comparator<URLPostClass>() {
#Override public int compare(URLPostClass lhs, URLPostClass rhs) {
return rhs.getTgglInsert().compareTo(lhs.getTgglInsert()); // flipped for reverse order
}
});
myListView.setAdapter(adapter);
Considering that you've got a Date field your Comaparator class would be like this
public class CustomDateComparator implements Comparator<DataProcessorResult> {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("dd MMM yyyy");
#Override
public int compare(DataProcessorResult lhs, DataProcessorResult rhs) {
// TODO Auto-generated method stub
Date lhsDate = null;
Date rhsDate = null;
try {
lhsDate = simpleDateFormat.parse(lhs.getTgglInsert());
rhsDate = simpleDateFormat.parse(rhs.getTgglInsert());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(lhsDate == rhsDate) {
return lhs.getNamaSales().compareToIgnoreCase(rhs.getNamaSales());
}else {
return lhsDate.compareTo(rhsDate);
}
}
}
And then you can do this
Collections.sort(results, new CustomDateComparator());
just before you pass it to your custom adapter class.
Hope this helps you.
This is my code , I have a problem ,error message about ResourcesNotFoundException this is a piece of code to view employees it has 2 buttons one to do delete and the other to do update.
I don't know the reason of this exception.
package com.example.task_9;
import java.util.ArrayList;
import com.example.task_9.my_dataBase.employees_con;
import com.example.task_9.my_dataBase.my_database;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class manage extends Activity {
ListView listview;
TextView totalrecords,tv;
//my_database db;
public ArrayList<employees> emp_list ;
employees_con con;
//Button logout;
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
setContentView(R.layout.manage);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Employees Record:");
totalrecords = (TextView) findViewById(R.id.textView2);
listview = (ListView) findViewById(R.id.listView1);
// logout=(Button) findViewById(R.id.button1);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
emp_list = new ArrayList<employees>();
emp_list.clear();
con = new employees_con(this);
// db = new my_database(getApplicationContext());
// db.getWritableDatabase();
ArrayList<employees> e_list =con.getAllData() ;
for (int i = 0; i < e_list.size(); i++) {
Log.d("for_getall ", "ok ");
int e_id = e_list.get(i).getId();
Log.d("fun_getall ", "ok ");
// System.out.println("tidno>>>>>" + tidno);
String e_name = e_list.get(i).getUser_name();
String e_password = e_list.get(i).getPassword();
int e_age = e_list.get(i).getAge();
int e_status = e_list.get(i).getStatus();
Log.d("fun_getall ", "ok ");
employees emp_model = new employees();
emp_model.setId(e_id);
emp_model.setUser_name(e_name);
emp_model.setPassword(e_password);
emp_model.setAge(e_age);
emp_model.setStatus(e_status);
Log.d("addlist ", "ok ");
emp_list.add(emp_model);
}
Log.d("out for ", "ok ");
totalrecords.setText("Total Records :-" + emp_list.size());
listview.setAdapter(new ListAdapter(this));
con.close();
}
private class ListAdapter extends BaseAdapter {
//ArrayList<employees> data=new ArrayList<employees>();
Context contxt;
TextView id;
TextView user_name;
TextView password;
TextView age;
TextView status;
ImageView img;
employees obj;
LayoutInflater inflater;
public ListAdapter(Context context) {
// TODO Auto-generated constructor stub
contxt=context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return emp_list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
/*if (v == null) {
v = inflater.inflate(R.layout.view, null);}*/
if (v == null)
{
LayoutInflater vi = (LayoutInflater)contxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.view, null); // album_list.xml this layout of the custom listview
Log.d("view if", "ok ");
}
id=(TextView) v.findViewById(R.id.textView6);
user_name=(TextView) v.findViewById(R.id.textView7);
password=(TextView) v.findViewById(R.id.textView8);
age=(TextView) v.findViewById(R.id.textView9);
status=(TextView) v.findViewById(R.id.textView10);
img =(ImageView) v.findViewById(R.id.imageView1);
Log.d("out if", "ok ");
obj = emp_list.get(position);
user_name.setText(obj.getUser_name());
id.setText(obj.getId());
password.setText(obj.getPassword());
age.setText(obj.getAge());
status.setText(obj.getStatus());
Log.d("view else ", "ok ");
final int temp = position;
(v.findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int emp_id=emp_list.get(temp).getId();
String emp_name = emp_list.get(temp).getUser_name();
String emp_password = emp_list.get(temp).getPassword();
int emp_age=emp_list.get(temp).getAge();
int emp_status=emp_list.get(temp).getStatus();
Intent intent = new Intent(manage.this,update.class);
Bundle bundle = new Bundle();
bundle.putInt("id", emp_id);
bundle.putString("name", emp_name);
bundle.putString("password", emp_password);
bundle.putInt("age", emp_age);
bundle.putInt("status", emp_status);
intent.putExtras(bundle);
startActivity(intent);
}
});
(v.findViewById(R.id.button2))
.setOnClickListener(new OnClickListener() {
employees_con con=new employees_con(contxt);
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(manage.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
con.DeleteEmp(emp_list.get(temp).getUser_name().toString());
con.close();
manage.this.onResume();
Toast.makeText(
getApplicationContext(),
"Record Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Toast.makeText(
getApplicationContext(),
"No Clicked...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
}
});
return v;
}
}
}
}
Change
id.setText(obj.getId());
with
id.setText(String.valueOf(obj.getId()));
if you pass an int as argument for a TextView android will look for a String with id the int you provide. If it does not found throws an exception
One important this is that you should use Activity.onCreate() method in place of Activity.onStart().
I have written a CustomAdapter to display a list of hash key+value items as a list. But I am stuck on the line below.
label.setText(my_VALUES[0])
Class two is my CustomAdapter and I am passing it a hashMap
public MyCustomAdapter(DynamicLists dynamicLists, int row, HashMap<String,String> data)
here I combine key+value pairs and I assign them to an array called my_VALUES. But I don't know if this is correct?
How can I print out each KEY+VALUE pair as a seperate item in getview. at the moment I can only use label.setText(my_VALUES[0])
Thanks
graham
package gb.org;
//lists are not checkboxes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
//class 1
public class DynamicLists extends ListActivity {
//class 2
public class MyCustomAdapter extends BaseAdapter {
private HashMap<String,String> mData = new HashMap<String,String>();
private String[] mKeys;
String[] my_VALUES = new String[100];
public MyCustomAdapter(DynamicLists dynamicLists, int row, HashMap<String,String> data){
mData = data;
mKeys = mData.keySet().toArray(new String[data.size()]);
Log.d(TAG, "INSIDE ADAPTER HELLO WORLD " + map.entrySet());
String[] array = new String[map.size()];
int count = 0;
String combined="";
for(Map.Entry<String, String> entry : map.entrySet()){
combined="A"+entry.getKey()+"B"+entry.getValue();
my_VALUES[count]=combined;
Log.d(TAG, " my_VALUES " + my_VALUES);
count++;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
String key = mKeys[position];
String Value = getItem(position).toString();
//do your view stuff here
Log.d(TAG, "inside getview ");
View row=convertView;
if (row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, null);
}
TextView label =(TextView)row.findViewById(R.id.blocked);
label.setText(my_VALUES[0]); //printing out the last value
return row;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mData.get(mKeys[position]);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
} //end of class 2
private static final String TAG = "Example";
//class 1
public static HashMap<String, String> map = new HashMap<String, String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//tie data to list, call constructor MyCustomAdapter
//populate the list. ArrayAdapter takes current class, layout and array
map.put("year", "Apple");
map.put("make", "Mango");
map.put("model", "Grape");
map.put("style", "Orange");
map.put("series", "Peach");
Log.d(TAG, "HELLO WORLD " + map.entrySet());
//link to my adapter
setListAdapter(new MyCustomAdapter(DynamicLists.this, R.layout.row, map));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//super.onListItemClick(l, v, position, id);
String selection = l.getItemAtPosition(position).toString();
Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
} //end of class 1
See if this works.
I only changed 2 things:
1) how my_VALUES is instantiated
2) label.setText(my_VALUES[position]);
public class DynamicLists extends ListActivity {
//class 2
public class MyCustomAdapter extends BaseAdapter {
private HashMap<String,String> mData = new HashMap<String,String>();
private String[] mKeys;
String[] my_VALUES;
public MyCustomAdapter(DynamicLists dynamicLists, int row, HashMap<String,String> data){
mData = data;
my_VALUES = new String[mData.size()];
mKeys = mData.keySet().toArray(new String[data.size()]);
Log.d(TAG, "INSIDE ADAPTER HELLO WORLD " + map.entrySet());
String[] array = new String[map.size()];
int count = 0;
String combined="";
for(Map.Entry<String, String> entry : map.entrySet()){
combined="A"+entry.getKey()+"B"+entry.getValue();
my_VALUES[count]=combined;
Log.d(TAG, " my_VALUES " + my_VALUES);
count++;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
String key = mKeys[position];
String Value = getItem(position).toString();
//do your view stuff here
Log.d(TAG, "inside getview ");
View row=convertView;
if (row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, null);
}
TextView label =(TextView)row.findViewById(R.id.blocked);
label.setText(my_VALUES[position]); //printing out the last value
return row;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mData.get(mKeys[position]);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
} //end of class 2
private static final String TAG = "Example";
//class 1
public static HashMap<String, String> map = new HashMap<String, String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//tie data to list, call constructor MyCustomAdapter
//populate the list. ArrayAdapter takes current class, layout and array
map.put("year", "Apple");
map.put("make", "Mango");
map.put("model", "Grape");
map.put("style", "Orange");
map.put("series", "Peach");
Log.d(TAG, "HELLO WORLD " + map.entrySet());
//link to my adapter
setListAdapter(new MyCustomAdapter(DynamicLists.this, R.layout.row, map));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//super.onListItemClick(l, v, position, id);
String selection = l.getItemAtPosition(position).toString();
Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
} //end of class 1
you are in java just do label.setText(mKeys[position] + getItem(position).toString());
I want to display my arraylist results by using custom list view.
for now i'm displaying my results by using android layout.
setListAdapter(new StudentListAdapter(this,android.R.layout.simple_list_item_1, results));
I've two fields to display
Locimage(Image from ImageUrl)
Locname (side by side)
files are here: ERROR/AndroidRuntime(335): Caused by: java.lang.NullPointerException
Since you're using a custom list adapter and you have overridden the getView method I think the following line:
setListAdapter(new StudentListAdapter(this,android.R.layout.simple_list_item_1, results));
Should be:
setListAdapter(new StudentListAdapter(this, results));
Refer API Demos for ListView with Multiple Views on it.
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html
Ultimately, you're going to need to override the getView() method of the adapter class you're using. Just a quick google search found plenty of examples.
Here's something really basic: http://sudarmuthu.com/blog/using-arrayadapter-and-listview-in-android-applications
And here's a more complex one: http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
try this code
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FindPlaces extends Activity{
private SQLiteDatabase DbLoc;
ListView lv;
private ArrayList<Fields> results = new ArrayList<Fields>();
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.places);
getallLocs();
displayLocs();
}
private void displayLocs() {
lv = (ListView)findViewById(R.id.listPlaces);
lv.setAdapter(new StudentListAdapter(this,results));
}
class StudentListAdapter extends BaseAdapter<Fields>{
private ArrayList<Fields> locationDetails;
private Context mContext;
public StudentListAdapter(Context context, ArrayList<Fields> results) {
// TODO Auto-generated constructor stub
System.out.println("Constructor StudentList Adapter...");
this.locationDetails = results;
this.mContext = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return locationDetails.size();
}
#Override
public Fields getItem(int position) {
// TODO Auto-generated method stub
return locationDetails.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(v == null){
LayoutInflater vl = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vl.inflate(R.layout.placeslist, null);
}
Fields o = locationDetails.get(position);
if (o != null) {
TextView iv = (TextView)v.findViewById(R.id.toptext);
TextView tv_sNo = (TextView)v.findViewById(R.id.toptext1);
iv.setText(o.getLocationName());
tv_sNo.setText(o.getLocationImage());
}
return v;
}
}
static class ViewHolder
{
TextView Locationname;
ImageView Locationimage;
}
private void getallLocs() {
// TODO Auto-generated method stub
try {
DatabaseHelper dbHelper = new DatabaseHelper(
this.getApplicationContext());
DbLoc = dbHelper.getWritableDatabase();
Cursor c = DbLoc.rawQuery("SELECT " + DatabaseHelper.LocationName+ " , " + DatabaseHelper.LocationImage + " FROM "
+ DatabaseHelper.LOCATIONTABLE , null);
if (c != null) {
if (c.moveToFirst()) {
do {
String LocationName= c.getString(c.getColumnIndex("LocationName"));
String Mobile = c.getString(c
.getColumnIndex("LocationImage"));
Fields p = new Fields(LocationName, Mobile);
results.add(p);
} while (c.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
}
finally { if (DbLoc != null) DbLoc.execSQL("DELETE FROM " +
DatabaseHelper.FRIENDTABLE); DbLoc.execSQL("DELETE FROM " +
DatabaseHelper.LOCATIONTABLE);
DbLoc.execSQL("DROP TABLE IF EXISTS tablename"+ DatabaseHelper.FRIENDTABLE);
DbLoc.execSQL("DROP TABLE IF EXISTS tablename"+ DatabaseHelper.LOCATIONTABLE);
DbLoc.close();
}
}
}