How to get image on an particular TextView String in android? - android

I am building an android application where the data is parsing from the JSON volley library.
Now my need is that: there Should be an particular image in front of particular Text in an ListView.
For example, if the data parsing string is ice-cream, then there should be an Ice-cream image in front of it.
Here is the code I am using for parsing data:
package tabsswipe;
public class FragmentPlay extends Fragment implements OnClickListener {
private Button ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;
// Movies json url
private static final String url = "url";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
String minstring, maxstring,finaldate;
EditText etxt1, etxt2;
String selItem, selItem2, selItem3, selItem4;
int ab, ba;
TextView tv1, tv2, txtsportname;
SeekBarWithTwoThumb swtt;
String firstlist;
public static ArrayList<String> array;
Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);
Spinner spnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
listView = (ListView) rootView.findViewById(R.id.list1);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int Position, long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
viewCategorysportdetails();
// Intent intent = new Intent(rootView.getContext(),
// SingleArticleAfrica.class);
// single.title = item.getTitle();
// single.author = item.getAuthor();
// single.date = item.getDate();
// single.featured_img = item.getFeatured_img();
// single.content = item.getContent();
// single.permalink = item.getPermalink();
firstlist = item.getTitle();
txtsportname.setText(firstlist);
// Toast.makeText(getActivity(), firstlist,
// Toast.LENGTH_LONG).show();
// startActivity(intent);
}
});
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
return rootView;
}
#Override
public void onStart() {
super.onStart();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("foodname"));
// movie.setThumbnailUrl(obj.getString("image"));
// movie.setRating(((Number) obj.get("rating"))
// .doubleValue());
// movie.setYear(obj.getInt("releaseYear"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Here is code where this parse value is add using CustomListAdapter:
package info.androidhive.customlistviewvolley.adater;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView rating = (TextView) convertView.findViewById(R.id.rating);
//TextView genre = (TextView) convertView.findViewById(R.id.genre);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
rating.setText((m.getRating()));
// release year
year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
Here is XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<ListView
android:id="#+id/list1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_row_selector" />
</RelativeLayout>
Here is ListAdapter XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_row_selector"
android:padding="8dp" >
<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/thumbnail"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp" />
<!-- Movie Title -->
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/title"
android:textStyle="bold" />
<!-- Rating -->
<TextView
android:id="#+id/rating"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/rating" />
<!-- Release Year -->
<TextView
android:id="#+id/releaseYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:textColor="#color/year"
android:textSize="#dimen/year" />

static List<String> foodnames = Arrays.asList((getResources().getStringArray(R.array.food_names)));
int key = foodnames.indexOf(getString(m.getFoodName()));
String[] food_name_drawables = context.getResources().getStringArray(R.array.food_name_drawables);
ImageView foodname = (ImageView) convertView.findViewById(R.id.image_foodname);
background.setBackgroundDrawable(context.getResources().getDrawable(food_name_drawables[key]);
I think it should work...

I hope I understood your need, but I'm not sure. Do you need to set as the background of the element view of the list an image representing the genre of the movie? Is that correct? If so:
If you take the infos from a server that you don't own, take a note of all the genres that the website uses, you put them in an array, and in the adapter depending on which genre is the movie of the list element, you change the background taking it from a drawable array. Let's say there are only 3 genres:
in xml:
<string-array name="movie_genres">
<item>Dramatic</item>
<item>Comedy</item>
<item>Action</item>
</string-array>
<string-array name"movie_genres_drawables">
<item>#drawable/dramatic_image</item>
<item>#drawable/comedy_image</item>
<item>#drawable/action_image</item>
</string-array>
then in the adapter:
static List<String> genres;
...
...
if (genres == null) {
genres = Arrays.asList((getResources().getStringArray(R.array.movie_genres)));
}
int key = genres.indexOf(getString(m.getGenre())); //Of course you should create this getter
String[] movie_genres_drawables = context.getResources().getStringArray(R.array.movie_genres_drawables);
ImageView background = (ImageView) convertView.findViewById(R.id.background);
background.setBackgroundDrawable(context.getResources().getDrawable(movie_genres_drawables[key]);
If you own the website with the movies archive, well you can take image directly from the server and put it on the list...
If I completely misunderstood your question, I'm sorry don't consider my answer at all. ;-)

Related

How to retreive data from mysql database in RecyclerView into RadioButton

Im creating a RecyclerView using jdbc connection and mysql database. Inside the RecyclerView I am uploading data from my database into one TextView and three radioButtons . Everything works just fine, but my problem is that it only shows the first RadioButton and there is nothing in the second and third one.
Here is my java code :
public class GererVoteInvite extends AppCompatActivity {
private ArrayList<VoteItem> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
private RecyclerView recyclerView; //RecyclerView
private RecyclerView.LayoutManager mLayoutManager;
private boolean success = false; // boolean
private static final String DB_URL = "jdbc:mysql://10.0.2.2/mvoting_db_1.0.0.0";
// private static final String DB_URL = "jdbc:mysql://172.16.24.25/mvoting_db_1.0.0.0"; //"jdbc:mysql://DATABASE_IP/DATABASE_NAME";
private static final String USER = "mootaz";
private static final String PASS = "mootaz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gerer_vote_invite);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView); //REcyclerview Declaration
recyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
itemArrayList = new ArrayList<VoteItem>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String> {
String msg = "Internet/DB_Credentials/Windows_FireWall_TurnOn Error, See Android Monitor in the bottom For details!";
ProgressDialog progress;
//Starts the progress dailog
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(GererVoteInvite.this, "Synchronising",
"RecyclerView Loading! Please Wait...", true);
}
// Connect to the database, write query and add items to array list
#Override
protected String doInBackground(String... strings) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); //Connection Object
if (conn == null) {
success = false;
} else {
// Change below query according to your own database.
String query = "SELECT lib_probleme , lib_solution_1 , lib_solution_2 , lib_solution_3 FROM reunion JOIN probleme JOIN solution WHERE reunion.id_reunion=probleme.id_reunion and probleme.id_probleme=solution.id_probleme ;";
Statement stmt = conn.createStatement();
java.sql.ResultSet rs = stmt.executeQuery(query);
// if resultset not null, I add items to itemArraylist using class created
if (rs != null) {
while (rs.next()) {
try {
itemArrayList.add(new VoteItem(rs.getString("lib_probleme"), rs.getString("lib_solution_1"), rs.getString("lib_solution_2"), rs.getString("lib_solution_3")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
// disimissing progress dialoge, showing error and setting up my gridview
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
Toast.makeText(GererVoteInvite.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, GererVoteInvite.this);
recyclerView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends RecyclerView.Adapter<MyAppAdapter.ViewHolder> {
private List<VoteItem> values;
public Context context;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtProbleme;
public RadioGroup group;
public RadioButton txtSol1;
public RadioButton txtSol2;
public RadioButton txtSol3;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
group = (RadioGroup) v.findViewById(R.id.radio_group);
txtProbleme = (TextView) v.findViewById(R.id.tv_probleme);
txtSol1 = (RadioButton) v.findViewById(R.id.rb_1);
txtSol2 = (RadioButton) v.findViewById(R.id.rb_2);
txtSol3 = (RadioButton) v.findViewById(R.id.rb_3);
}
}
// Constructor
public MyAppAdapter(List<VoteItem> myDataset, Context context) {
values = myDataset;
this.context = context;
}
// Create new views (invoked by the layout manager) and inflates
#Override
public MyAppAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.vote_view, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Binding items to the view
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final VoteItem voteItem = values.get(position);
holder.txtProbleme.setText(voteItem.getProbleme());
holder.group.setTag(position);
holder.txtSol1.setText(voteItem.getSol1());
holder.txtSol2.setText(voteItem.getSol2());
holder.txtSol3.setText(voteItem.getSol3());
}
// get item count returns the list item count
#Override
public int getItemCount() {
return values.size();
}
}
}
And here is my layout.xml that containt the item for the RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/ac"
android:layout_width="match_parent"
android:layout_height="205dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:padding="5dp">
<android.support.v7.widget.CardView
android:id="#+id/vote_card"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#color/white"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="5dp">
<TextView
android:id="#+id/tv_probleme"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginTop="30dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="Probleme :"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16dp" />
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/rb_1"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginTop="60dp"
android:text="Solution 1" />
<RadioButton
android:id="#+id/rb_2"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="Solution 2" />
<RadioButton
android:id="#+id/rb_3"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="Solution 3" />
</RadioGroup>
</android.support.v7.widget.CardView>
</RelativeLayout>
Here is the screenshot of my app

Is there anyway I can change my code to recycleview for icons in android?

I have an activity where items are coming from database , and i want set icons for the same. I tried listview but heard about recyclerview , but I cant seem to find the solution as to how can I load it. kindly help
here is my listview:
public class TypeMenu extends AppCompatActivity {
private String TAG = TypeMenu.class.getSimpleName();
String bid;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud....com/brtemp/index.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String selectedId= selected.get("id");
Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
in.putExtra("id",selectedId);
startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" +selectedId ,Toast.LENGTH_SHORT).show();
}
});
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(TypeMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("type", type);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, new String[]{ "type","id"},
new int[]{
R.id.type});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
/>
<TextView
android:id="#+id/type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ImageView
android:id="#+id/arrow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
/>
</LinearLayout>
</LinearLayout>
try this:
here is lsit_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp" />
<TextView
android:id="#+id/type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp" />
</LinearLayout>
<ImageView
android:id="#+id/arrow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"/>
</LinearLayout>
initialize this in your activity;
int[] images = new int[]{
R.drawable.dropdown,
};
// Keys used in Hashmap
String[] from = { "image","id","type" };
// Ids of views in listview_layout
int[] to = { R.id.arrow1,R.id.id,R.id.type};
In your doInbanckground
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("type", type);
contact.put("image", Integer.toString(images[0]) );
contactList.add(contact);
}
Also add this in your onPostExecute replacing above code:
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, from,to);
lv.setAdapter(adapter);
You need to create custom RecylerView adapter
Step 1: gradle:
dependencies {
...
compile "com.android.support:recyclerview-v7:23.0.1"
}
Step 2: layout/activity_name.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
Step 3: Create Custom Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<String> mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView txtHeader;
public TextView txtFooter;
public ViewHolder(View v) {
super(v);
txtHeader = (TextView) v.findViewById(R.id.firstLine);
txtFooter = (TextView) v.findViewById(R.id.secondLine);
}
}
public MyAdapter(ArrayList<String> myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = mDataset.get(position);
holder.txtHeader.setText(mDataset.get(position));
holder.txtHeader.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
remove(name);
}
});
holder.txtFooter.setText("Footer: " + mDataset.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
Step 4: In your activity.java
setContentView(R.layout.my_activity);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);

i want to fetch a data from database and display it on listview.

xml file
the first file is a xml file of the design.
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listviewtask"/>
</LinearLayout>
</RelativeLayout>
rawtask.xml file
this is the raw file and here design of a list view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/property_display_box"
android:id="#+id/listview1ll">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Task Name"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:id="#+id/lvtaskname" />
<TextView
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:hint="Task Details"
android:layout_gravity="center"
android:id="#+id/lvtaskdetails"
/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Details"
android:layout_marginLeft="40dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:id="#+id/lvchkbox"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:orientation="horizontal"
android:id="#+id/lvl1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:text="Remaining Time:"
android:textSize="20dp"
android:id="#+id/lvrt"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
android:layout_marginLeft="90dp"
android:layout_marginTop="10dp"
android:textSize="20dp"
android:id="#+id/lvdone"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Listviewadapter.java
the listviewadapter.java is shown
public class ListViewAdapter2 extends BaseAdapter {
Context cntx;
AlertDialog.Builder alertDialogBuilder;
//int loader = R.drawable.ic_menu_gallery;
ArrayList<String> t_id=new ArrayList<String>();
ArrayList<String> t_tname=new ArrayList<String>();
ArrayList<String> t_detail=new ArrayList<String>();
// ArrayList<Float> itemRating=new ArrayList<Float>();
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
//ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
/*
* public ListViewAdapter(Context context, ArrayList<HashMap<String,
* String>> arraylist) { this.cntx = context; data = arraylist; imageLoader
* = new ImageLoader(context); }
*/
public ListViewAdapter2(Context context,
ArrayList<String> taskid,
ArrayList<String> taskname,
ArrayList<String> taskdetail) {
// TODO Auto-generated constructor stub
cntx = context;
t_id=taskid;
t_tname = taskname;
t_detail =taskdetail;
//Log.d("xyz", security_id.toString());
//ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
//ImageLoader.getInstance().init(config);
alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage("Do You Want To Call....");
// itemRating=itm_rating;
}
#Override
public int getCount() {
return t_id.size();
}
#Override
public Object getItem(int position) {
return t_id.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressWarnings("deprecation")
public View getView(final int position, View convertView, ViewGroup parent) {
#SuppressWarnings("unused")
final TextView taskname, taskdetail;
inflater = (LayoutInflater) cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(cntx);
convertView = inflater.inflate(R.layout.rawtask, parent, false);
/*ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(loader)
.showImageOnFail(loader)
.showImageOnLoading(loader).build();*/
taskname= (TextView) convertView.findViewById(R.id.lvtaskname);
taskdetail= (TextView) convertView.findViewById(R.id.lvtaskdetails);
taskname.setText("taskName : "+t_tname.get(position));
taskdetail.setText("taskdetail: "+t_detail.get(position));
return convertView;
}
}
main activity.java
this is the final .java file of the project
package com.example.sachin.listview;
public class Main2Activity extends Fragment {
public Main2Activity(){};
private static final String TAG_SUCCESS = "success";
JSONArray jsonarray;
JSONObject jsonobject;
ListView listview;
String img;
ListViewAdapter2 listadapter;
//ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
private static String url_task = "http://10.0.2.2/portal/aFetchtask.php";
// private static String url_profile ="http://10.0.2.2/myapp/fetchmember.php";
JSONParser jParser = new JSONParser();
ArrayList<String> t_id = new ArrayList<String>();
ArrayList<String> t_tname = new ArrayList<String>();
ArrayList<String> t_detail = new ArrayList<String>();
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
// don't look at this layout it's just a listView to show how to handle the keyboard
View view = inflater.inflate(R.layout.activity_main, container, false);
getActivity().setTitle("tasks");
new DownloadJSON().execute();
return view;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
//mProgressDialog = new ProgressDialog(getActivity());
//mProgressDialog.setTitle("Please Wait");
// Set progressdialog message
//mProgressDialog.setMessage("Loading...");
//mProgressDialog.setIndeterminate(false);
// Show progressdialog
//mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args) {
// Create an array
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("abc", "abc"));
JSONObject json = jParser.makeHttpRequest(url_task, "POST", params);
int success1 = Integer.parseInt(json.getString(TAG_SUCCESS));
Log.d("success", json.toString());
if (success1 == 0) {
Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
}
if (success1 == 1) {
JSONArray ownerObj = json.getJSONArray("tasks");
// arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
// Locate the array name in JSON
// jsonarray = jsonobject.getJSONArray("images");
for (int i = 0; i < ownerObj.length(); i++) {
// HashMap<String, String> map = new HashMap<String, String>();
jsonobject = ownerObj.getJSONObject(i);
// Retrive JSON Objects
//securityId.add(jsonobject.getString("security_id"));
// t_id.add(jsonobject.getString("t_id"));
t_tname.add(jsonobject.getString("t_tname"));
t_detail.add(jsonobject.getString("t_detail"));
// Number.add(jsonobject.getString("number"));
Log.d("DATA", jsonobject.toString());
//img="http://10.0.2.2/momskitchen/image/";
//proImage.add(img + jsonobject.getString("image"));
/* System.out.println(jsonobject.getString(TA));
System.out.println(g);*/
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) getActivity().findViewById(R.id.listviewtask);
ListViewAdapter2 listadapter = new ListViewAdapter2(getActivity(), t_id, t_tname, t_detail);
// Set the adapter to the ListView
listview.setAdapter(listadapter);
// Close the progressdialog
//mProgressDialog.dismiss();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
// outState = result.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
}
and the lastly is the file is my api file..
<?php
include("connection.php");
$response = array();
// get all products from products table
$result = mysql_query("SELECT * FROM task") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["tasks"] = array();
while ($row = mysql_fetch_array($result))
{
$tasks = array();
$tasks["t_id"] = $row["t_id"];
$tasks["t_tname"] = $row["t_tname"];
$tasks["t_udetail"] = $row["t_udetail"];
// push single product into final response array
array_push($response["tasks"], $tasks);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else
{
// no products found
$response["success"] = 0;
$response["message"] = "No picture found";
// echo no users JSON
echo json_encode($response);
}
?>
here the all files are available.
but the data is not fetched from the database.
please help me out for this..
There are lot of coding faults are there.
The Asynchronus class is return types are not in the exact manner to retrive the data.
After protected Void doInBackground(Void... args) {}is returning null then you can get null value to onPostExcute(Void args) you have to write get whole repose in doInBackground() method only if you are not returning any response.
In rawtask.xml file should contains views which are inflating by adapter but in your case other view are mentioned.
So refere this following link to get the data from webservices into listView.
here

Android Gridview - Not able to select image inside Griditem with Android-Box remote

I am creating a android app in which i have list of channels(items) in a Custom GridView.
I have a favorite icon associated with each channel to add them in favorites list.
On click of this favorite icon the channel gets added to the Favorites List of channels.
When i use a android box remote i am not able to select the ImageView for favorite.
Instead the whole GridItem gets selected.
The single grid item is a LinearLayout which mainly has two ImageViews in it.
View code for a single grid-item of the gridview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="false"
android:clickable="true"
android:orientation="vertical" >
<ImageView
android:id="#+id/channelLogo"
android:layout_width="75dip"
android:layout_height="75dip"
android:layout_gravity="center"
android:focusable="false"
android:contentDescription="#string/app_name"/>
<TextView
android:id="#+id/channelName"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<TextView
android:id="#+id/channelStatus"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<ImageView
android:id="#+id/addToFavourite"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="false"
android:contentDescription="Add to favourites"
android:src="#drawable/addfavorites"
/>
</LinearLayout>
Code for my grid adapter where i handle the click of the ImageView (for adding a channel to favorite).
public class GridAdapter extends BaseAdapter {
private Context mContext;
private int resourceId;
private ArrayList<Item> itemList = new ArrayList<Item>();
private ArrayList<Category> categoryList = new ArrayList<Category>();
private int size;
private Integer[] mThumbIds;
private ViewGroup gridGroup;
private static final String PREFS_FAVOURITES = "favourites";
public GridAdapter(MainActivity c, int layoutResourceId, ArrayList<Item> data, int gsize) {
mContext = c;
resourceId = layoutResourceId;
itemList = data;
size = gsize;
mThumbIds = new Integer[gsize];
for(int i=0;i<mThumbIds.length;i++) {
mThumbIds[i] = R.drawable.ic_launcher;
}
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int arg0) {
return mThumbIds[arg0];
}
#Override
public long getItemId(int arg0) {
return arg0;
}
class ViewHolder {
ImageView imageUrl;
TextView channelNameTxt;
TextView channelStatusTxt;
ImageView imgFavourite;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String contextClass = mContext.getClass().toString();
ViewHolder holder;
gridGroup = parent;
View grid = null;
if(convertView==null){
grid = new View(mContext);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
if (contextClass.contains("MainActivity") || contextClass.contains("FavoriteActivity")) {
grid = inflater.inflate(R.layout.grid_item, parent, false);
}
}else{
grid = (View)convertView;
return grid;
}
if (contextClass.contains("MainActivity")) {
if (position < itemList.size()) {
holder = new ViewHolder();
holder.channelNameTxt = (TextView) grid
.findViewById(R.id.channelName);
String channelName = itemList.get(position).getChannelName().replace("\n", "").replace("\r", "");
holder.channelNameTxt.setText(channelName);
holder.channelStatusTxt = (TextView) grid
.findViewById(R.id.channelStatus);
holder.channelStatusTxt
.setText(itemList.get(position).getStatus());
if(itemList.get(position).getStatus().equalsIgnoreCase("Online")) {
holder.channelStatusTxt.setTextColor(Color.GREEN);
} else if(itemList.get(position).getStatus().equalsIgnoreCase("Offline")) {
holder.channelStatusTxt.setTextColor(Color.RED);
}
holder.imageUrl = null;
try {
holder.imageUrl = (ImageView) grid
.findViewById(R.id.channelLogo);
holder.imageUrl.setTag(itemList.get(position).getImageUrl());
new DownloadImagesTask().execute(holder.imageUrl);
notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex.toString());
}
final Item info = itemList.get(position);
holder.imgFavourite = (ImageView)grid.findViewById(R.id.addToFavourite);
holder.imgFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//GridView gridview1;
if(mContext.getClass().toString().contains("MainActivity")) {
GridView gv = (GridView)gridGroup;
final int position = gv.getPositionForView((View) v.getParent());
Toast.makeText(mContext, "Position is :" + position, Toast.LENGTH_SHORT).show();
SharedPreferences settings = mContext.getSharedPreferences(PREFS_FAVOURITES, 0);
String favourites = settings.getString("favourites", "");
Item clicked_item = itemList.get(position);
String sep1 = "<sep1>";
String sep = "<sep>";
String favourite = clicked_item.getChannelUrl()+sep1+clicked_item.getChannelName()+sep1+clicked_item.getStatus()+sep1+"Favorite"+sep1+clicked_item.getImageUrl()+sep;
favourite = favourite.replace("\n", "").replace("\r", "");
if(!favourites.contains(favourite))
favourites = favourites+favourite;
SharedPreferences.Editor editor = settings.edit();
editor.putString("favourites", favourites);
editor.commit();
}
}
});
grid.setTag(holder);
}
}
return grid;
}
This works fine on a android phone.

Remove items from a Custom ListView (Android)

How do I create a neverending listview of list items with checkboxes that can be removed with a delete item button? The answer is below.
In order to create a neverending listview the first thing you need to have is a set of two runnables. These threads will update the array of data in your adapter.
final int itemsPerPage = 100;
ArrayList<HashMap<String,String>> listItems = new ArrayList<HashMap<String,String>>();
boolean loadingMore = false;
int item = 0;
//Since we cant update our UI from a thread this Runnable takes care of that!
public Runnable returnRes = new Runnable() {
#Override
public void run() {
//Loop thru the new items and add them to the adapter
if(groceries.getGroceries().size() > 0){
for(int i=0;i < listItems.size();i++) {
HashMap<String,String> grocery = listItems.get(i);
adapter.add(grocery);
}
//Update the Application title
setTitle("Grocery List with " + String.valueOf(groceries.getGroceries().size()) + " items");
//Tell to the adapter that changes have been made, this will cause the list to refresh
adapter.notifyDataSetChanged();
//Done loading more.
loadingMore = false;
}
}
};
//Runnable to load the items
public Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
listItems = new ArrayList<HashMap<String,String>>();
//Get 8 new listitems
for (int i = 0; i < itemsPerPage; i++) {
if (i < groceries.getGroceries().size()) {
listItems.add(groceries.getGroceries().get(i));
item++;
}
}
//Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
Then your onCreate() method should look something like this with an array passed to your adapter:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_grocery_list);
//add the footer before adding the adapter, else the footer will not load!
View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.activity_footer_view, null, false);
this.getListView().addFooterView(footerView);
adapter = new ListViewAdapter(this,groceries);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//Here is where the magic happens
this.getListView().setOnScrollListener(new OnScrollListener(){
//useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
//dumdumdum
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//what is the bottom iten that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already ? Load more !
if((lastInScreen == totalItemCount) && !loadingMore && item < groceries.getGroceries().size()){
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
}
You will also need a delete method to remove the items with checkboxes and a checkOff method as well. They look like this:
ArrayList<Integer> checkedBoxes = new ArrayList<Integer>();
ArrayList<HashMap<String,String>> checkedItems = new ArrayList<HashMap<String,String>>();
public void deleteItem(View view) {
if (checkedBoxes.size() > 1 || checkedBoxes.size() == 0) {
Toast.makeText(getApplicationContext(), "You can only delete one item at a time. Sorry :(", Toast.LENGTH_LONG).show();
return;
} else {
checkedItems.add(groceries.getGroceries().get(checkedBoxes.get(0)));
groceries.getGroceries().removeAll(checkedItems);
checkedBoxes.clear();
try {
groceries.serialize();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(),CreateGroceryList.class);
startActivity(intent);
}
}
public void checkOff(View view) {
CheckBox box = (CheckBox)view;
DataModel d = (DataModel)box.getTag();
if(!checkedBoxes.contains(d.index)) {
checkedBoxes.add(d.index);
} else {
checkedBoxes.remove((Integer)d.index);
}
}
In order to communicate with the adapter it is helpful to have a DataModel class that will model our information. My DataModel has an index variable to keep track of the selected item.
public class DataModel {
int index;
HashMap<String,String> data;
boolean selected;
public DataModel(int i) {
index = i;
data = new HashMap<String,String>();
selected = false;
}
public HashMap<String, String> getData() {
return data;
}
public void setData(HashMap<String, String> data) {
this.data = data;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
Finally, here is the code for the BaseAdapter:
public class ListViewAdapter extends BaseAdapter {//To create an adapter we have to extend BaseAdapter instead of Activity, or whatever.
private ListActivity activity;
private View vi;
private ArrayList<DataModel> data;
private static LayoutInflater inflater=null;
public ListViewAdapter(ListActivity a, GroceryList g) {
activity = a;
data = new ArrayList<DataModel>();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
groceries = g;
}
public void add(HashMap<String,String> a){
DataModel d = new DataModel(data.size());
d.setData(a);
d.setSelected(false);
data.add(d);
}
public ArrayList<DataModel> getData() {
return data;
}
public int getCount() { //get the number of elements in the listview
return data.size();
}
public Object getItem(int position) { //this method returns on Object by position
return position;
}
public long getItemId(int position) { //get item id by position
return position;
}
public View getView() {
return vi;
}
public View getView(int position, View convertView, ViewGroup parent) { //getView method is the method which populates the listview with our personalized rows
vi=convertView;
final ViewHolder holder = new ViewHolder();
if(convertView==null) {
vi = inflater.inflate(R.layout.custom_row_view, null);
//every item in listview uses xml "listview_row"'s design
holder.name = (CheckBox)vi.findViewById(R.id.name);
holder.price = (TextView)vi.findViewById(R.id.price); // You can enter anything you want, buttons, radiobuttons, images, etc.
holder.quantity = (TextView)vi.findViewById(R.id.quantity);
holder.name
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
DataModel element = (DataModel) holder.name
.getTag();
element.setSelected(buttonView.isChecked());
}
});
vi.setTag(holder);
holder.name.setTag(data.get(position));
ViewHolder vholder = (ViewHolder) vi.getTag();
vholder.name.setChecked(data.get(position).isSelected());
HashMap<String, String> hash = new HashMap<String, String>(); //We need a HashMap to store our data for any item
hash = data.get(position).getData();
vholder.name.setText(hash.get("brand") + " " + hash.get("name")); //We personalize our row's items.
vholder.price.setText("$" + hash.get("price"));
vholder.quantity.setText("Quantity: " + hash.get("quantity"));
} else {
vi = convertView;
((ViewHolder) vi.getTag()).name.setTag(data.get(position));
}
if (holder.name == null) {
ViewHolder vholder = (ViewHolder) vi.getTag();
vholder.name.setChecked(data.get(position).isSelected());
HashMap<String, String> hash = new HashMap<String, String>(); //We need a HashMap to store our data for any item
hash = data.get(position).getData();
vholder.name.setText(hash.get("brand") + " " + hash.get("name")); //We personalize our row's items.
vholder.price.setText("$" + hash.get("price"));
vholder.quantity.setText("Quantity: " + hash.get("quantity"));
}
return vi;
}
}
class ViewHolder {
CheckBox name;
TextView price;
TextView quantity;
public CheckBox getName() {
return name;
}
public void setName(CheckBox name) {
this.name = name;
}
public TextView getPrice() {
return price;
}
public void setPrice(TextView price) {
this.price = price;
}
public TextView getQuantity() {
return quantity;
}
public void setQuantity(TextView quantity) {
this.quantity = quantity;
}
}
You also need a few xml files in your layout folder this is what they will look like:
You need a footerview that will tell your list when to load new items:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:gravity="center_horizontal"
android:padding="3dp"
android:layout_height="fill_parent">
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="5dp"
android:text="Add more grocery items..."/>
A custom row view that is populated by your BaseAdapter:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox"
android:focusable="false"
android:textSize="25dip"
android:onClick="checkOff"
/>
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dip"
android:text="Lastname"
android:textSize="15dip" />
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dip"
android:text="Lastname"
android:textSize="15dip" />
</LinearLayout>
And a parent view, mine is called create_grocery_list because I'm writing a grocery list editor: This one must contain a ListView with the proper id.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="400dp" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
</LinearLayout>
<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="72dp" >
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="105dp"
android:layout_y="0dp"
android:onClick="deleteItem"
android:text="#string/deleteItem" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="8dp"
android:layout_y="0dp"
android:onClick="goToAddItemScreen"
android:text="#string/addItem" />
<Button
android:id="#+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="221dp"
android:layout_y="0dp"
android:onClick="scanner"
android:text="#string/scanCode" />
</AbsoluteLayout>
</LinearLayout>
And that's about it... hope this helps anyone. It's the most complete tutorial you'll find.
I learned all this from this tutorial: http://www.vogella.com/articles/AndroidListView/article.html#androidlists_overview then added the two runnables to make a neverending grocery list :) have fun programming...

Categories

Resources