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();
}
}
}
Related
I have a ListView that displays a list of items and I want to display further more details when any item is clicked using StringBuffer. But I'm having an issue because android default setOnItemClickListener bypasses the StringBuffer view that I'm defining inside the click event, and just displays the the item view in a popup.
Here is my code and I will include some screen shots in order to clarify my point a bit more
import android.app.AlertDialog;
import android.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
public class SummerJobsFragmnet extends Fragment {
public SummerJobsFragmnet() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static Fragment getInstance() {
Fragment fragment = new SummerJobsFragmnet();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void showMessage (String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final MainActivity activity = (MainActivity) getActivity();
String [] places = activity.getAllPositionsNamesPhone().toArray(
new String[activity.getAllPositionsNamesPhone().size()]);
final ListView list = (ListView) getView().findViewById(R.id.joblistView);
int prgmImages=R.mipmap.ic_launcher;
list.setAdapter(new CustomListAdapter(activity,places,prgmImages));
// OnClick listner for the individual cells of the listView
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the IDs of each column in the database
String [] IDs = activity.getAllColumnsIDs().toArray(
new String[activity.getAllColumnsIDs().size()]);
// loop throught the IDs and see if they match the listView
// item ids. if yes, display the detail
DataBaseHelper summerJobDB;
summerJobDB = new DataBaseHelper(activity);
for (int i = 0; i >= IDs.length; i++) {
if (i == id) {
Cursor res = summerJobDB.getAllData();
if (res.getCount() ==0){
// show some message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
// append the values from the database to the buffer.
// this is based on the index number of the columns
while (res.moveToNext()) {
buffer.append(res.getString(1)+ "/" + res.getString(2) +"\n");
buffer.append("Starts on " + res.getString(3)+"\n\n");
buffer.append("Address: \n"+ res.getString(5)+"\n\n");
buffer.append("Phone: \n"+ res.getString(6)+"\n\n");
buffer.append("Hours: \n"+ res.getString(4)+"\n\n");
}
// show all data here
showMessage("Data",buffer.toString());
}
}
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.displayjobs, container, false);
}
}
and here is the CustomListAdapter.java
import android.widget.BaseAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomListAdapter extends BaseAdapter {
String [] result;
Context context;
int imageId;
private static LayoutInflater inflater=null;
public CustomListAdapter(MainActivity mainActivity, String[] places, int prgmImages) {
// TODO Auto-generated constructor stub
result=places;
context=mainActivity;
imageId=prgmImages;
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 position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.display_job_cell_view, null);
holder.tv=(TextView) rowView.findViewById(R.id.Itemname);
holder.img=(ImageView) rowView.findViewById(R.id.icon);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId);
/*
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
*/
return rowView;
}
}
first image
Here is what I get
here is the logcat error after making the modifications
You have defined onClickListener on your list-items (rowView.setOnClickListener) - this is what gets called instead of the listView's setOnItemClickListener. You need to remove (comment out) this in the CustomListAdapter class:
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
You need to also call listView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); so that only the listView's item click listener can be invoked even if the row item of list are set as focusable or clickable.
Then the dialog should show as you'd expect. Please try this and let us know if it works or what errors you get.
I have create a listview activity which opens dialog boxes on item click. In the dialog box, the users can enter different value 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? Thanks !!!
NoteAdapter.java
package com.cngcnasaud.orar;
import java.util.Arrays;
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.ImageView;
import android.widget.TextView;
public class NoteAdapter extends BaseAdapter {
String[] result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
private Dialog dialog;
String[] savedEntries;
String[] saved = null;
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);
if (saved == null) {
savedEntries = new String[result.length];
Arrays.fill(savedEntries, "");
} else
savedEntries = saved;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return savedEntries[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
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.text.setText(savedEntries[position]);
holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
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);
savedEntries[position] = data;
dialog.dismiss();
Log.d("data", data);
}
});
dialog.show();
}
});
return rowView;
}
}
Note.java :
package com.cngcnasaud.orar;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Note extends Activity {
public static final ListAdapter NoteAdapter = null;
ListView lv;
Context context;
ArrayList<?> prgmName;
TextView text;
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);
text = (TextView) findViewById(R.id.textView2);
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;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
// Variable is public for clarity.
String toSave = EncodeDecode.encode(adapter.savedEntries);
SharedPreferences.Editor editor = getSharedPreferences("LV Data",
MODE_PRIVATE).edit();
editor.putString("TVEntries", toSave);
editor.commit();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
SharedPreferences prefs = getSharedPreferences("LV Data", MODE_PRIVATE);
String encoded = prefs.getString("TVEntries", "");
String[] entries;
if (encoded.equals(""))
entries = null;
else
entries = EncodeDecode.decode(encoded);
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
adapter.savedEntries = entries;
lv.setAdapter(adapter);
super.onResume();
}
}
Here's a proposed solution involving SharedPreferences:
First, add a String[] instance variable to your Adapter class. This will contain what you want to save(the fields inside your TextViews. Initialize this your constructor.
public NoteAdapter(Note note, String[] saved, String[] prgmNameList, int[] prgmImages) {
result=prgmNameList;
context=note;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
/**********INSERTED CODE********/
if(saved == null) {
savedEntries = new String[result.length];`
Arrays.fill(savedEntires, "");
}
else
savedEntries = saved;
/****************************/
}
Also modify your overriden getItem() method to return the appropriate element in savedEntires:
#Override
public Object getItem(int position) {
return savedEntries[position];
}
Whenever you update a TextView, update the list accordingly:
#Override
public void onClick(View v) {
String data = txtMode.getText().toString();
holder.text.setText(data);
/***INSERTED CODE****/
savedEntries[position] = data;
/*******************/
dialog.dismiss();
Log.d("data", data);
}
We will save this array in SharedPreferences using a String-String pair. Since Strings can potentially contain any character, it is difficult/inefficient to find a single delimiter. I implemented a class called EncodeDecode that can encode a String array into a single formatted String, and decode it back to a String array here: https://gist.github.com/liangricha/10759438. I'll be using this class to convert/unconvert savedEntries.
Whenever you want to save savedEntries(in onStop()), simply execute this code:
ListView lv = //... get reference
NoteAdapter adapter = (NoteAdapter)lv.getAdapter();
//Variable is public for clarity.
String toSave = EncodeDecode.encode(adapter.savedEntries);
SharedPreferences.Editor editor = getSharedPreferences("LV Data", MODE_PRIVATE).editor();
editor.putString("TVEntries", toSave);
editor.commit();
When you want to retrieve the String array of your TextView entries(in onResume()), execute:
SharedPreferences prefs = getSharedPreferences("LV Data", MODE_PRIVATE);
String encoded = prefs.getString("TVEntries", "");
String[] entries
if(encoded.equals(""))
entries = null;
else
entries = EncodeDeocde.decode(encoded);
NoteAdapter adapter = (NoteAdapter)lv.getAdapter();
adapter.savedEntries = entries;
lv.setAdapter(adapter);
Then, in your getView() method of 'NoteAdapter', set the field of the TextView to the appropriate entry in savedEntries:
holder.text.setText(savedEntries[position]);
I'm trying to add a Custom ListView With an Adapter to a Fragment.
I don't Know where is the problem exactly, I think I got everything in place yet I cant get rid of the Unfortunately Stopped message.
I Used the debug and knew where it all collapses ;
in the Fragment class at the
for (int i = 0;i<4;i++){
.
.
.
questions.add(question);
when the debug reaches this statement it ends.
Fragment
import java.util.List;
import code.me.R.id;
import android.R.layout;
import android.app.Application.ActivityLifecycleCallbacks;
import android.app.Fragment;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
#SuppressLint("NewApi")
public class Fragment1 extends Fragment
{
ListView lv;
List<Question> questions;
Integer[] Q_Id ;
String[] AskerUserName = {"Jack" ,"John" ,"Lio" ,"Sam" ,"Mike" };
String[] AnswererUserName ={"Jacob" ,"Mario" ,"Tom" ,"Shon" ,"Jasmine" };
String[] Qusetion = {"What?" ,"Where?" ,"When" ,"How?" ,"Who?" };
String[] Answer = {"jjjjjjjjjj","llllllll","fffffffff","eeeeeeeeeeee","oooooooooooo"};
#Override
public View onCreateView( LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState )
{
for (int i = 0;i<4;i++){
int qid = i;
String AUName = AskerUserName[i].toString();
String AnUName = AnswererUserName[i].toString();
String Ans = Answer[i].toString();
String Ques = Qusetion[i].toString();
Question question = new Question(qid, AUName, AnUName, Ans, Ques);
questions.add(question);
}
View view = inflater.inflate(R.layout.frag1, container, false);
QuestionsAdapter questad = new QuestionsAdapter(getActivity(),questions);
lv = (ListView) view.findViewById(id.listView1);
lv.setAdapter(questad);
return inflater.inflate( R.layout.frag1,
container, false );
}
}
Adapter
import java.util.List;
import code.me.R.id;
import android.R.layout;
import android.app.Activity;
import android.content.Context;
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;
public class QuestionsAdapter extends BaseAdapter {
private final Activity context;
public List<Question> questions;
LayoutInflater inflater;
public QuestionsAdapter(Activity context,List<Question> qu) {
this.context = context;
this.questions = qu;
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View view , ViewGroup parent){
View rowView = view;
if(view == null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.question_answer_item, null,false);
TextView askerUserName = (TextView) view.findViewById(id.askerUsername);
askerUserName.setText(questions.get(position).getAskerUserName().toString());
TextView question = (TextView) view.findViewById(id.Question);
question.setText(questions.get(position).getQuestion().toString());
TextView ratingView = (TextView) view.findViewById(id.RatingAsker);
//ratingView.setText(questions.get(position)._RatingU);
TextView ratingAnswerer = (TextView) view.findViewById(id.RatingAnswerer);
//ratingAnswerer.setText(questions.get(position).getRatingView());
return rowView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return questions.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return questions.get(position)._QId;
}
}
Class_Question
public class Question {
private
String _Answer ;
String _AnswererUserName;
String _AskerUserName ;
String _Question ;
Integer _QId;
Integer _RatingU;
Integer _RatingQ;
public Question (int Q_Id,String AUName,String AnUName,String Ans,String Ques){
_QId = Q_Id;
_AnswererUserName = AnUName;
_AskerUserName = AUName;
_Answer = Ans;
_Question = Ques;
}
public String getAnswer() {
// TODO Auto-generated method stub
return _Answer;
}
public String getAnswererUserName() {
// TODO Auto-generated method stub
return _AnswererUserName;
}
public String getAskerUserName() {
// TODO Auto-generated method stub
return _AskerUserName;
}
public String getQuestion() {
// TODO Auto-generated method stub
return _Question;
}
public int getRatingView() {
// TODO Auto-generated method stub
return _RatingU;
}
public void setRatingQ() {
// TODO Auto-generated method stub
}
public int getRatingQ() {
// TODO Auto-generated method stub
return _RatingQ;
}
}
You never initialize the List<Question> questions in your fragment.
You never initialize your question collection. That's why it stops when you try to add questions in onCreateView. Either initialize List questions initially or some time before you try to add things to it.
Android 2.3.3
I have seen few questions at stackoverflow, regarding refreshing the listview. But none of them worked for me.
I have a dynamic listview and I have a button inside it. The data is being populated from database and each listview row is a custom layout. On press of the (Clear) button, the database is cleared(which works fine) and the listview should get refreshed(the part to be figured out).
Below is the code...
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.mobilevoiceapps.advancedvoicecalculatorfree.R;
public class History extends ListActivity {
ListView lvHistory;
ArrayAdapter<String> adHistory;
ArrayList<String> alHistoryCopy = new ArrayList<String>();
String[] emptyList = { "Your Calculations History is Empty. Please Perform Some Calculations and visit again." };
Database db;
Cursor c;
String expression = "";
String result = "";
boolean isEmpty = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// setContentView(R.layout.history);
lvHistory = getListView();
final MyCustomAdapter myad = new MyCustomAdapter();
db = new Database(this);
c = db.retrieve_history();
if (!((c.moveToFirst()) || c.equals(null) || c.getCount() == 0)) {
} else if (c.getCount() > 0) {
c.moveToFirst();
}
LayoutInflater header = getLayoutInflater();
View header_View = header.inflate(R.layout.history_header, null);
lvHistory.addHeaderView(header_View);
View second_Header_View = header.inflate(
R.layout.history_second_header, null);
lvHistory.addHeaderView(second_Header_View);
Button btnClearHistory = (Button) second_Header_View
.findViewById(R.id.btnClearHistory);
btnClearHistory.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.clear_history();
myad.notifyDataSetChanged();
lvHistory.invalidateViews();
lvHistory.refreshDrawableState();
}
});
lvHistory.setAdapter(myad);
}
class MyCustomAdapter extends BaseAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return c.getCount();
}
#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 convertView, ViewGroup parent) {
// TODO Auto-generated method stub
HistoryViewHolder viewHolder;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
convertView = li.inflate(R.layout.history_row, null);
viewHolder = new HistoryViewHolder();
viewHolder.txtcnt = (TextView) convertView
.findViewById(R.id.txtView_History_Count);
viewHolder.txtexp = (TextView) convertView
.findViewById(R.id.txtView_History_Expression);
viewHolder.txtres = (TextView) convertView
.findViewById(R.id.txtView_History_Result);
convertView.setTag(viewHolder);
} else {
viewHolder = (HistoryViewHolder) convertView.getTag();
}
viewHolder.txtcnt.setText(String.valueOf(position + 1));
System.out.println("Position"
+ viewHolder.txtcnt.getText().toString());
c.moveToPosition(position);
expression = c.getString(c.getColumnIndex("expression"));
result = c.getString(c.getColumnIndex("result"));
viewHolder.txtexp.setText(expression);
System.out.println("Expression"
+ viewHolder.txtexp.getText().toString());
viewHolder.txtres.setText(result);
System.out.println("Result"
+ viewHolder.txtres.getText().toString());
return convertView;
}
public class HistoryViewHolder {
TextView txtcnt;
TextView txtexp;
TextView txtres;
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (db != null) {
db.close();
}
if (c != null) {
c.close();
}
}
}
EDIT ::: With ScreenShots :::
Try to extend your MyCustomAdapter from BaseAdapter and use notifyDataSetChanged to refresh ListView.
The better way to display database content is CursorAdapter (or CursorLoader) - such adapters listen for update notifications and reloads the content automatically.
try this, You need to refresh you ListView after delete one item using myad.notifyDataSetChanged();
btnClearHistory.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
YourActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
myad.notifyDataSetChanged();
}
});
}
});
Try add c = db.retrieve_history(); after db.clear_history();.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.clear_history();
c = db.retrieve_history();
myad.notifyDataSetChanged();
lvHistory.invalidateViews();
lvHistory.refreshDrawableState();
}
Hope this helped you.
Just restart your activity..
ActivityName.this.finish();
Intent intent=new Intent(this, ActivityName.class);
startActivity(intent);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_loja, container, false);
listatividade = (ListView) view.findViewById(R.id.listservico);
String[] valueatividade = new String[] { "atividade 1",
"atividade 2",
"atividade 3" };
adapteratividade = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, valueatividade);
listatividade.setAdapter(adapteratividade);
listaatividade.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int itemPosition = position;
String itemValue = (String) listaatividade.getItemAtPosition(position);
Toast.makeText(getActivity(), "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG) .show();
updateData();
}
});
return view;
}
private void updateData() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
String[] valueatividade = new String[] { "atividade 4", "atividade 5", "atividade 6" };
adapteratividade = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, android.R.id.text1, valueatividade);
listatividade.setAdapter(adapteratividade);
}
});
}
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);