set button onclick in listview android - android

i have a listView with list item like this.
i want to set an action at button "Edit" and "Delete".
this is my code.
listitem.xml
<?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:padding="5dp"
android:orientation="vertical" >
<TextView
android:id="#+id/varId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<TextView
android:id="#+id/varNoNota"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textStyle="bold"
android:padding="2dp"
/>
<TextView
android:id="#+id/varSenderName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/varNoNota"
android:padding="2dp"
/>
<TextView
android:id="#+id/varTotalAmount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/varSenderName"
android:padding="2dp"
/>
<Button
android:id="#+id/btnEdit"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#color/YellowGreen"
android:text="#string/Edit"
/>
<Button
android:id="#+id/btnDelete"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignBottom="#+id/varTotalAmount"
android:layout_alignRight="#+id/varTotalAmount"
android:background="#color/Red"
android:text="#string/Delete" />
</RelativeLayout >
this is resigteritem.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="vertical"
android:background="#color/LimeGreen">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/registerItem"
android:textSize="20sp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip"
android:text="#string/from" />
<EditText
android:id="#+id/dateFrom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip"
android:text="#string/to" />
<EditText
android:id="#+id/dateTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp" />
<Button
android:id="#+id/btnSearchRegisterItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#color/YellowGreen"
android:text="#string/search" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp"
android:background="#color/DarkGray">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:layout_below="#+id/btnSearchRegisterItem"
/>
</LinearLayout>
</LinearLayout>
this is my code at file java.
public class registerItem extends Activity {
private Context context = this;
private EditText dateFrom;
private EditText dateTo;
private Calendar c = Calendar.getInstance();
private int day = c.get(Calendar.DAY_OF_MONTH);
private int month = c.get(Calendar.MONTH);
private int year = c.get(Calendar.YEAR);
private static String url = "http:localhost:8080/exdar/api/registerItem/list";
private static final String RegisterItemList = "registerItemList";
private static final String NoNota = "noNota";
private static final String SenderName = "senderName";
private static final String TotalAmount = "totalAmount";
private static final String ID = "id";
private boolean isFrom = false;
private Button btnSubmit;
private Button btnDelete;
private Button btnEdit;
ListView list;
private static String content ;
private static String from;
private static String to;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private DatePickerDialog.OnDateSetListener dateSetListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
String finalDate = pad(dayOfMonth) + "/" + pad(monthOfYear + 1)
+ "/" + year;
if (isFrom) {
dateFrom.setText(finalDate);
} else {
dateTo.setText(finalDate);
}
}
public String pad(int data) {
if (data < 10) {
return "0" + data;
} else {
return String.valueOf(data);
}
}
};
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 1) {
return new DatePickerDialog(context, dateSetListener, year, month,
day);
}
return null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.registeritem);
setUpView();
list = (ListView) findViewById(R.id.list);
}
private void setUpView() {
// TODO Auto-generated method stub
dateFrom = (EditText) findViewById(R.id.dateFrom);
dateTo = (EditText) findViewById(R.id.dateTo);
btnSubmit = (Button) findViewById(R.id.btnSearchRegisterItem);
btnEdit = (Button) findViewById(R.id.btnEdit);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
oslist.clear();
System.out.println("before JSON parse .........!!!!");
new JSONParse().execute();
System.out.println("after JSON parse .........!!!!");
}
});
dateFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(1);
isFrom = true;
}
});
dateTo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(1);
isFrom = false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class JSONParse extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(registerItem.this);
pDialog.setMessage("Getting List Item ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
System.out.println("masuk on preexecute");
}
#Override
protected Void doInBackground(Void... params) {
System.out.println("masuk doin background");
SimpleDateFormat dateparse = new SimpleDateFormat("dd/MM/yyyy");
HttpUtils networkGet = HttpUtils.getInstance();
System.out.println("networkGet = "+networkGet);
from = dateFrom.getText().toString();
System.out.println("from = "+from);
to = dateTo.getText().toString();
System.out.println("to = "+to);
try {
try{
ArrayList<NameValuePair> parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("from", from));
parameter.add(new BasicNameValuePair("to", to));
content = MyHttpURLConnection.postToHTTPJSON(url,parameter);
}
catch(Exception e){
System.out.print(e);
}
// Getting JSON Object from URL Content
JSONObject json = new JSONObject(content);
JSONArray jsonArray = json.getJSONArray(RegisterItemList);
for (int i = 0; i < jsonArray.length(); i++)
{
System.out.println("looping ke = "+i);
JSONObject c = jsonArray.getJSONObject(i);
System.out.println("c = "+c);
// Storing JSON item in a Variable
String id = c.getString(ID);
System.out.println("id "+id);
String noNota = c.getString(NoNota);
System.out.println("noNota = "+noNota);
String senderName = c.getString(SenderName);
System.out.println("senderName = "+senderName);
String totalAmount = c.getString(TotalAmount);
System.out.println("totalAmount = "+totalAmount);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(ID,id);
map.put(NoNota, noNota);
map.put(SenderName, senderName);
map.put(TotalAmount, totalAmount);
oslist.add(map);
System.out.println("oslist = "+oslist);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
list.setAdapter(new customadapter(oslist,getApplicationContext()));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(
registerItem.this,
"You Clicked at "
+ oslist.get(+position).get(NoNota),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
i tried add this code to see if my code run with correctly then the toast will be show but i got error;
i got this error
i am trying to create a baseadapter..
package com.example.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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.Button;
import android.widget.TextView;
import android.widget.Toast;
public class customadapter extends BaseAdapter{
ArrayList<HashMap<String, String>> oslist;
Context context;
private Button btnDelete;
private Button btnEdit;
public customadapter(ArrayList<HashMap<String, String>> oslist, Context context) {
context = context;
oslist = oslist;
this.oslist = oslist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
System.out.println("oslist.size() = "+oslist.size());
return oslist.size();
}
#Override
public Map.Entry<String, String> getItem(int position) {
// TODO Auto-generated method stub
return (Map.Entry) oslist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater lif = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = lif.inflate(R.layout.listitem, null);
TextView txt_Name = (TextView) convertView.findViewById(R.id.varId);
Button btnEdit = (Button) convertView.findViewById(R.id.btnEdit);
btnEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("mybutton in listview already works!!");
//Here perform the action you want
}
});
return convertView;
}
}

Try to use BaseAdapter Instead of ListAdapter it will be easier
Here i'm giving sample code you can implement like this in your code,
public class BaseAdapContact extends BaseAdapter {
List<String> liName;
Context con;
public BaseAdapContact(List<String> liName, Context con) {
this.liName = liName;
this.con = con;
}
#Override
public int getCount() { // TODO Auto-generated method stub
return liName.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater lif = (LayoutInflater) con
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = lif.inflate(R.layout.list_view, null);
TextView txt_Name = (TextView) convertView.findViewById(R.id.txtName);
Button btn_Call = (Button) convertView.findViewById(R.id.btnCall);
txt_Name.setText(liName.get(position));
btn_Call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Here perform the action you want
}
});
return convertView;
}
}

As per my aspect you should initialized your list in setUpView();
list = (ListView) findViewById(R.id.list);
Your app is crash at
list.invalidateViews();
list.setAdapter(adapter);
in onPostExecute(Void result) at this line list==null

Where is your list adapter???
You should set onClickListner on a button inside your list adapter

you should use interface to listen Click Event.
Here is example,
First, you need to create a interface in adapter.
public interface onListItemClickListener{
void onEditClick();
void onDeleteClick();
}
And then implement onListItemClickListener in your registerItem activity. It will need to implement two methods in your activity.
in click event from your adapter, for ex
btn_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//you will contain Context from your parent activity
//cast your context to listener coz it implement that listener
onListItemClickListener listener = (onListItemClickListener) mContext;
// you can add parameter in method
listener.onEditClick();
//Done this will call your method in your activity.
}
});
Hope this will help you.

Related

Expandable listview in android using json parsing

I have a problem with expandable ListView. The problem is that the list shows the group fields only, not the children. I am using expandable listview in navigation drawer.
This is my activity class:
public class NewsTabActivity extends Activity {
public static String Id, LOGO, WEB_SERV, SUB_CAT, Font;
ImageView image;
ImageLoader imgloader;
String URL_MAIN_CAT, nDrawerSubCat, URL_SUB_CAT, URL_HOME_PAGE;
String[] mainCatName, mainCatId, mainCatId1, subCatParentID;
JSONArray jarray,jarray1;
private DrawerLayout mDrawerLayout;
private ExpandableListView mDrawerList;
private ListView homeListview;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
ArrayList<NewsList> newsList;
public ArrayList<NewsDrawerItem> navDrawerItems;
public HashMap<NewsDrawerItem, ArrayList<NewsDrawerItem>> navDrawerChildItems;
private NewsDrawerItem newsDrawerItems;
private NewsDrawerListAdapter adapter;
NewsListAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hometab);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.list_slidermenu);
homeListview = (ListView) findViewById(R.id.listView1);
homeListview.setVisibility(View.VISIBLE);
image = (ImageView) findViewById(R.id.imageView1);
imgloader = new ImageLoader(NewsTabActivity.this);
imgloader.DisplayImage(LOGO, image);
nDrawerSubCat = SUB_CAT;
System.out.println("DRAWER_SUBCAT ? = "+nDrawerSubCat);
URL_HOME_PAGE = WEB_SERV + "homenews.php";
URL_MAIN_CAT = WEB_SERV + "maincategory.php";
if(nDrawerSubCat.equalsIgnoreCase("yes")) {
URL_SUB_CAT = WEB_SERV + "subcategory.php";
System.out.println("DRAWER_SUBCAT = "+URL_SUB_CAT);
}
newsList = new ArrayList<NewsList>();
navDrawerItems = new ArrayList<NewsDrawerItem>();
navDrawerChildItems = new HashMap<NewsDrawerItem, ArrayList<NewsDrawerItem>>();
if (WebserviceUtils.isConnectingToInternet(NewsTabActivity.this)) {
new NewsHomePage().execute(URL_HOME_PAGE);
new NewsPaperMainCat().execute(URL_MAIN_CAT);
}
// adding nav drawer items to array
mDrawerList.setOnGroupClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
getActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle("News Live");
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("News Live");
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView();
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ExpandableListView.OnGroupClickListener,ExpandableListView.OnGroupExpandListener {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// TODO Auto-generated method stub
displayView();
homeListview.setVisibility(View.GONE);
NewsListActivity.valuesID(navDrawerItems.get(groupPosition).getId());
NewsListActivity.valueWEBSERV(WEB_SERV);
System.out.println("NEWS_LIST_ID = "+navDrawerItems.get(groupPosition).getId());
return false;
}
#Override
public void onGroupExpand(int groupPosition) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
navDrawerItems.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
return super.onOptionsItemSelected(item);
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView() {
// update the main content by replacing fragments
Fragment fragment = null;
fragment = new NewsListActivity();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("NewsTabActivity", "Error in creating fragment");
}
}
private class NewsHomePage extends AsyncTask<String, String, String> {
private ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(NewsTabActivity.this, "",
"Loading...Please wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
JsonParsor json = new JsonParsor();
JSONObject jobject = json.getJSONFromUrl(URL_HOME_PAGE);
try {
JSONArray jarray = jobject.getJSONArray("news");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobj = jarray.getJSONObject(i);
String id = jobj.getString("Id");
String cid = jobj.getString("c_id");
String title = jobj.getString("title");
String image = jobj.getString("image");
NewsList news = new NewsList();
news.setId(jobj.getString("Id"));
news.setCid(jobj.getString("c_id"));
news.setTitle(jobj.getString("title"));
news.setImage(jobj.getString("image"));
newsList.add(news);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "sucess";
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
p_dialog.dismiss();
if (result.compareTo("sucess") == 0) {
adapter1 = new NewsListAdapter(NewsTabActivity.this,
R.layout.newslist_single_item, newsList);
homeListview.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
} else {
Toast.makeText(NewsTabActivity.this, "No data Found...",
Toast.LENGTH_LONG).show();
}
}
}
private class NewsPaperMainCat extends AsyncTask<String, String, String> {
private ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(NewsTabActivity.this, "",
"Loading...Please wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
JsonParsor json = new JsonParsor();
JSONObject jobject,jobject1=null;
int j,i;
ArrayList<NewsDrawerItem> item = new ArrayList<NewsDrawerItem>();
navDrawerItems = new ArrayList<NewsDrawerItem>();
navDrawerChildItems = new HashMap<NewsDrawerItem, ArrayList<NewsDrawerItem>>();
jobject = json.getJSONFromUrl(URL_MAIN_CAT);
if(nDrawerSubCat.equalsIgnoreCase("yes")) {
jobject1 = json.getJSONFromUrl(URL_SUB_CAT);
}
try {
jarray = jobject.getJSONArray("categories");
if(nDrawerSubCat.equalsIgnoreCase("yes")) {
jarray1 = jobject1.getJSONArray("categories");
}
for (i = 0; i < jarray.length(); i++) {
JSONObject jobj = jarray.getJSONObject(i);
mainCatName = new String[jarray.length()];
mainCatId = new String[jarray.length()];
mainCatId[i] = jobj.getString("Id");
mainCatName[i] = jobj.getString("name");
String id = jobj.getString("Id");
String name = jobj.getString("name");
System.out.println("MAIN_ID = " + id + " NAME= " + name);
// adding nav drawer items to array
navDrawerItems.add(new NewsDrawerItem(mainCatName[i], mainCatId[i]));
}
if(nDrawerSubCat.equalsIgnoreCase("yes")) {
for (j = 0; j < jarray1.length(); j++) {
JSONObject jobj = jarray1.getJSONObject(j);
// newsDrawerItems = new NewsDrawerItem();
mainCatName = new String[jarray.length()];
mainCatId1 = new String[jarray.length()];
subCatParentID = new String[jarray.length()];
mainCatId1[j] = jobj.getString("Id");
mainCatName[j] = jobj.getString("name");
subCatParentID[j] = jobj.getString("parent_id");
String id = jobj.getString("Id");
String name = jobj.getString("name");
String pID = jobj.getString("parent_id");
System.out.println("MAIN_SUB_ID = "+id+" NAME= "+name+" PARENT_ID = "+pID);
item = new ArrayList<NewsDrawerItem>();
item.add(new NewsDrawerItem(mainCatName[j], mainCatId1[j]));
}
item = new ArrayList<NewsDrawerItem>();
item.add(new NewsDrawerItem(mainCatName[j], mainCatId1[j]));
navDrawerChildItems.put(navDrawerItems.get(j), item);
}
} catch (Exception e) {
// TODO: handle exception
}
return "sucess";
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
p_dialog.dismiss();
super.onPostExecute(result);
if (result.compareTo("sucess") == 0) {
adapter = new NewsDrawerListAdapter(NewsTabActivity.this,
navDrawerItems, navDrawerChildItems);
mDrawerList.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else
Toast.makeText(NewsTabActivity.this, "No data Found...",
Toast.LENGTH_LONG).show();
}
}
public static void valueID(String id) {
// TODO Auto-generated method stub
Id = id;
}
public static void valueLogo(String logo) {
// TODO Auto-generated method stub
LOGO = logo;
}
public static void valueWebService(String webServ) {
// TODO Auto-generated method stub
WEB_SERV = webServ;
}
public static void valueSubCat(String subCat) {
// TODO Auto-generated method stub
SUB_CAT = subCat;
}
public static void valueFont(String font) {
// TODO Auto-generated method stub
Font = font;
}
}
This is my Adapter class:
public class NewsDrawerListAdapter extends BaseExpandableListAdapter {
Context context;
public ArrayList<NewsDrawerItem> navDrawerItems;
public HashMap<NewsDrawerItem, ArrayList<NewsDrawerItem>> navDrawerChildItems;
public NewsDrawerListAdapter(
Context context,
ArrayList<NewsDrawerItem> navDrawerItems,
HashMap<NewsDrawerItem, ArrayList<NewsDrawerItem>> navDrawerChildItems) {
this.context = context;
this.navDrawerItems = navDrawerItems;
this.navDrawerChildItems = navDrawerChildItems;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
// TODO Auto-generated method stub
return this.navDrawerChildItems.get(
this.navDrawerItems.get(groupPosition)).get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosititon) {
// TODO Auto-generated method stub
return childPosititon;
}
#Override
public View getChildView(int groupPosition, int childPosititon,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.drawer_listchild_item,
null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.title_child);
txtListChild.setText("sdv");
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
System.out.println("getChildrenCount_GROUP_POS = "
+ navDrawerItems.get(groupPosition).getChildItem().size());
return navDrawerItems.get(groupPosition).getChildItem().size();
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return this.navDrawerItems.get(groupPosition);
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
System.out.println("GROUP_COUNT = " + navDrawerItems.size());
return this.navDrawerItems.size();
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater
.inflate(R.layout.drawer_list_item, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.title);
lblListHeader.setText(Html.fromHtml(navDrawerItems.get(groupPosition).getTitle()));
return convertView;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
}
This is the model class:
public class NewsDrawerItem {
private String title, Id, PId;
private int icon;
private ArrayList<NewsDrawerItem> childItemList = new ArrayList<NewsDrawerItem>();
public NewsDrawerItem() {
}
public NewsDrawerItem(String title, String Id) {
this.title = title;
this.Id = Id;
}
public NewsDrawerItem(String title, String Id, String PId) {
this.title = title;
this.Id = Id;
this.PId = PId;
}
public String getTitle() {
return this.title;
}
public String getId() {
return this.Id;
}
public String getPId() {
return this.PId;
}
public int getIcon() {
return this.icon;
}
public ArrayList<NewsDrawerItem> getChildItem() {
System.out.println("CHILD_ITEM = "+childItemList);
return childItemList;
}
public void setTitle(String title) {
this.title = title;
}
public void setId(String Id) {
this.Id = Id;
}
public void setPId(String PId) {
this.PId = PId;
}
public void setIcon(int icon) {
this.icon = icon;
}
public void setChildItem(ArrayList<NewsDrawerItem> childItemList) {
this.childItemList = childItemList;
}
}
THIS IS WORK FOR ME TRY IT
This is HomeFragment java class
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.TextView;
import android.widget.Toast;
public class HomeFragment extends Fragment {
private static String url = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";
private ProgressDialog mprocessingdialog;
private TextView tv_welcomeuser, tv_recentupdate;
private ExpandableListAdapter expandableListAdapter;
private ExpandableListView exp_leaseoffer;
private List<String> listDataHeader;
private View rootView;
private HashMap<String, List<String>> listDataChild;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.wellcome_page, container, false);
tv_welcomeuser = (TextView) rootView.findViewById(R.id.tv_welcomeuser);
tv_recentupdate = (TextView) rootView
.findViewById(R.id.tv_recentupdate);
exp_leaseoffer = (ExpandableListView) rootView.findViewById(R.id.lvExp);
new DownloadJason().execute();
return rootView;
}
private class DownloadJason extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mprocessingdialog = new ProgressDialog(getActivity());
mprocessingdialog.setTitle("Please Wait..");
mprocessingdialog.setMessage("Loading");
mprocessingdialog.setIndeterminate(false);
mprocessingdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
listDataHeader = new ArrayList<String>();
JSONParser jp = new JSONParser();
String jsonstr = jp.makeServiceCall(url, JSONParser.GET);
Log.d("Json url view", jsonstr);
if (jsonstr != null) {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
try {
JSONObject jobj = new JSONObject(jsonstr);
JSONArray jarray = jobj.getJSONArray("worldpopulation");
for (int hk = 0; hk < jarray.length(); hk++) {
JSONObject d = jarray.getJSONObject(hk);
// Adding Header data
listDataHeader.add(d.getString("country"));
// Adding child data for lease offer
List<String> lease_offer = new ArrayList<String>();
lease_offer.add(d.getString("country") + "'s Rank is : "
+ d.getString("rank"));
lease_offer.add("And Population is "+d.getString("population"));
// Header into Child data
listDataChild.put(listDataHeader.get(hk), lease_offer);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(),
"Please Check internet Connection", Toast.LENGTH_SHORT)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mprocessingdialog.dismiss();
expandableListAdapter = new info.tranetech.adurec.fragments.Expandable_adapter(
getActivity(), listDataHeader, listDataChild);
Log.i("groups", listDataHeader.toString());
Log.i("details", listDataChild.toString());
exp_leaseoffer.setAdapter(expandableListAdapter);
exp_leaseoffer.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// TODO Auto-generated method stub
return false;
}
});
// Listview Group expanded listener
exp_leaseoffer
.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
// Toast.makeText(getActivity().getApplicationContext(),
// listDataHeader.get(groupPosition) + " Expanded",
// Toast.LENGTH_SHORT).show();
}
});
exp_leaseoffer
.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(
getActivity().getApplicationContext(),
listDataHeader.get(groupPosition)
+ " Collapsed", Toast.LENGTH_SHORT)
.show();
}
});
exp_leaseoffer.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// Toast.makeText(
// getActivity().getApplicationContext(),
// listDataHeader.get(groupPosition)
// + " : "
// + listDataChild.get(
// listDataHeader.get(groupPosition)).get(
// childPosition), Toast.LENGTH_SHORT)
// .show();
// Intent ilk = new Intent(getActivity(),
// Lease_Offer_one.class);
// startActivity(ilk);
return false;
}
});
}
}
// public Boolean isWifiAvailable() {
//
// try {
// ConnectivityManager connectivityManager = (ConnectivityManager)
// getActivity()
// .getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo wifiInfo = connectivityManager
// .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//
// if (wifiInfo.isConnected()) {
// return true;
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return false;
// }
// public boolean isNetworkAvailable() {
// ConnectivityManager connectivityManager = (ConnectivityManager)
// getActivity()
// .getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo activeNetworkInfo = connectivityManager
// .getActiveNetworkInfo();
// return activeNetworkInfo != null && activeNetworkInfo.isConnected();
// }
}
**This is Expandable_adapter java class**
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class Expandable_adapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader;
private HashMap<String, List<String>> _listDataChild;
public Expandable_adapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listDataChild) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listDataChild;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_child, null);
}
TextView expandedListTextView = (TextView) convertView
.findViewById(R.id.tv_listchild);
expandedListTextView.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_group, null);
}
TextView listTitle = (TextView) convertView
.findViewById(R.id.tv_listtitle);
listTitle.setTypeface(null, Typeface.BOLD);
listTitle.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
**xml wellcome_page**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#drawable/background_welcome" >
<LinearLayout
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:background="#drawable/bottom_bar"
android:orientation="horizontal" >
</LinearLayout>
<TextView
android:id="#+id/tv_welcomeuser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="WELCOME USER"
android:textColor="#FFFFFF"
android:textSize="16sp"
tools:ignore="HardcodedText" />
<LinearLayout
android:id="#+id/eeeee"
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_below="#+id/tv_welcomeuser"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/edit_text"
android:gravity="center" >
<TextView
android:id="#+id/tv_recentupdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:singleLine="true"
android:text="RECENT UPDATES"
android:textColor="#FFFFFF"
android:textSize="18sp"
tools:ignore="HardcodedText" />
</LinearLayout>
<RelativeLayout
android:id="#+id/expl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/header"
android:layout_alignParentLeft="true"
android:layout_below="#+id/eeeee"
android:layout_marginTop="20dp" >
<LinearLayout
android:id="#+id/textLin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="vertical"
android:weightSum="4" >
<TextView
android:id="#+id/tv_adurec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/lvExp"
android:layout_centerHorizontal="true"
android:layout_weight="1"
android:fontFamily="times_roman"
android:text=" Powered by "
android:textColor="#ffffff"
android:textSize="15dp"
tools:ignore="ObsoleteLayoutParam,HardcodedText,SpUsage" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/tv_adurec"
android:layout_centerVertical="true"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:text="ADUREC"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff"
tools:ignore="ObsoleteLayoutParam,HardcodedText" />
</LinearLayout>
<ExpandableListView
android:id="#+id/lvExp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textLin"
android:listSelector="#drawable/buttons_effacts"
android:divider="#color/list_divider"
android:dividerHeight="0.8dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ExpandableListView>
</RelativeLayout>
</RelativeLayout>
**list_child.xml **
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="#+id/tv_listchild"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:paddingTop="10dp"
android:textSize="16sp"
android:gravity="center"
android:textColor="#7D1023"
android:background="#ffffff"
android:paddingBottom="10dp" />
</LinearLayout>
**list_group.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="vertical" >
<TextView
android:id="#+id/tv_listtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/buttons_effacts"
android:padding="15dp"
android:gravity="center"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textColor="#ffffff"
android:textSize="16sp" />
</LinearLayout>

edittext value not save in listview dynamically

in my listview already 20 items and above listview there is one "ADD" button .when i am click on button then open one popup dialog.. in popup dialog there is on edittext and save and close button .. when i am write something edittext and click on save button then its not working.... i'll use custom listview with one image left side and text in center..... help me
Button add = (Button)findViewById(R.id.btn_Add);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.popup);
dialog.setTitle("Add Category");
Button close = (Button)dialog.findViewById(R.id.btn_cls);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
Button save = (Button)dialog.findViewById(R.id.btn_sv);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText)dialog.findViewById(R.id.editText1);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
});
dialog.show();
}
});
Try this way,hope this will help you to solve your problem.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#drawable/black"
android:orientation="vertical">
<EditText
android:id="#+id/search"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/bbbb"
android:ems="10"
android:textColor="#color/White"
android:hint="Search"
android:padding="5dp"
android:textSize="20sp">
<requestFocus />
</EditText>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="10dp"
android:dividerHeight="5dp"
android:cacheColorHint="#null"
android:listSelector="#null"
android:clipToPadding="false"
android:drawSelectorOnTop="true" />
<Button
android:id="#+id/btn_Add"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/list_selector"
android:text="ADD Category"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
listview_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/button_border"
android:gravity="center"
android:padding="5dp">
<ImageView
android:id="#+id/flag"
android:background="#drawable/sd"
android:layout_width="60dp"
android:layout_height="60dp"
android:adjustViewBounds="true"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dp">
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="21sp"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/round"
android:layout_marginLeft="5dp"/>
</LinearLayout>
popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<Button
android:id="#+id/btn_cls"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:text="Close" />
<Button
android:id="#+id/btn_sv"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="#drawable/list_selector"
android:text="Save" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private ListView list;
private ListViewAdapter adapter;
private EditText editsearch;
private Button add;
private String[] animal = new String[] {"COW","LION","TIGER","ELEPHANT","MONKEY","DONKEY"};
private ArrayList<String> listData;
private Dialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listview);
add = (Button)findViewById(R.id.btn_Add);
listData = new ArrayList<String>();
for (int i=0;i<animal.length;i++){
listData.add(animal[i]);
}
Collections.sort(listData);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addAnimal();
}
});
adapter = new ListViewAdapter(this,listData);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,listData.get(position),Toast.LENGTH_SHORT).show();
// if(listData.get(position).equals("COW"));
// intent = new Intent(getBaseContext(),COW.class);
//
// else if(listData.get(position).equals("LION"))
// intent = new Intent(getBaseContext(),LION.class);
//
// else if(listData.get(position).equals("TIGER"))
// intent = new Intent(getBaseContext(),TIGER.class);
//
// else if(listData.get(position).equals("MONKEY"))
// intent = new Intent(getBaseContext(),MOKEY.class);
//
// else if(listData.get(position).equals("DONKEY"))
// intent = new Intent(getBaseContext(),DONKEY.class);
}
});
editsearch = (EditText) findViewById(R.id.search);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
String text = editsearch.getText().toString();
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
}
public void addAnimal(){
dialog = new Dialog(this);
dialog.setContentView(R.layout.popup);
dialog.setTitle("Add Animal");
final EditText edit = (EditText)dialog.findViewById(R.id.editText1);
Button close = (Button)dialog.findViewById(R.id.btn_cls);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button save = (Button)dialog.findViewById(R.id.btn_sv);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(edit.getText().toString().trim().length()>0){
listData.add(edit.getText().toString());
Collections.sort(listData);
adapter = new ListViewAdapter(MainActivity.this,listData);
list.setAdapter(adapter);
dialog.dismiss();
}else{
edit.setError("Value Required");
}
}
});
dialog.show();
}
class ListViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> data;
private ArrayList<String> filterData;
public ListViewAdapter(Context context,ArrayList<String> data) {
this.context = context;
this.data = data;
filterData =new ArrayList<String>();
filterData.addAll(this.data);
}
public class ViewHolder {
TextView country;
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.listview_item, null);
holder.country = (TextView) view.findViewById(R.id.country);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.country.setText(filterData.get(position));
return view;
}
public void filter(String charText) {
filterData.clear();
if (charText.length() == 0) {
filterData.addAll(data);
}else{
for (String animal : data){
if (animal.toLowerCase().contains(charText.toLowerCase())){
filterData.add(animal);
}
}
}
notifyDataSetChanged();
}
}
}
i will use like that..
public class list extends Activity {
private ListView list;
private Button add ;
private Dialog dialog;
private ListViewAdapter adapter;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView)findViewById(R.id.listview1);
add = (Button)findViewById(R.id.btn_Addd);
listData = new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AddSMS();
}
});
list.setAdapter(adapter);
}
public void AddSMS(){
dialog = new Dialog(this);
dialog.setContentView(R.layout.popup1);
dialog.setTitle("Add Your SMS");
final EditText et = (EditText)dialog.findViewById(R.id.editText11);
Button close = (Button)dialog.findViewById(R.id.btn_clss);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button save = (Button)dialog.findViewById(R.id.btn_svv);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (et.getText().toString().trim().length()>0){
listData.add(et.getText().toString());
adapter = new ListViewAdapter(list.this, listData);
list.setAdapter(adapter);
dialog.dismiss();
}else {
et.setError("Value Required");
}
}
});
dialog.show();
}
class ListViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> data;
private ArrayList<String> filterData;
public ListViewAdapter(Context context,ArrayList<String> data) {
this.context = context;
this.data = data;
filterData =new ArrayList<String>();
filterData.addAll(this.data);
}
public class ViewHolder {
TextView txttt;
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.list_double, null);
holder.txttt = (TextView) view.findViewById(R.id.txttt);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txttt.setText(filterData.get(position));
return view;
}
public void filter(String charText) {
filterData.clear();
if (charText.length() == 0) {
filterData.addAll(data);
}else{
for (String Detail : data){
if (Detail.toLowerCase().contains(charText.toLowerCase())){
filterData.add(Detail);
}
}
}
notifyDataSetChanged();
}
}
}
instead of add to list add the item in adapter and then call notifyDataSetChanged

EditText show in a ListView

public class MainActivity extends Activity {
Button okButton;
EditText wishEditText;
ListView wishListView;
BaseAdapter adapter;
ArrayList<list_item>arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_main);
initializedAll();
}
public void initializedAll() {
okButton = (Button) findViewById(R.id.button1);
wishEditText = (EditText) findViewById(R.id.editText1);
wishListView = (ListView) findViewById(R.id.listView1);
arrayList = new ArrayList<list_item>();
adapter = new BaseAdapter() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View view, ViewGroup viewGroupgroup) {
if (view==null) {
view = inflater.inflate(R.layout.wish_list_item, null);
}
TextView wishText = (TextView) findViewById(R.id.wishItemtextView);
TextView dateText = (TextView) findViewById(R.id.wishDatetextView);
wishText.setText(arrayList.get(position).getWishString());
Date date = arrayList.get(position).getDate();
dateText.setText(DateFormat.format("dd/MM/yyyy HH:mm:ss a", date));
return view;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
};
wishListView.setAdapter(adapter);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String string = wishEditText.getText().toString();
Date date = new Date();
list_item item = new list_item(date,string);
arrayList.add(item);
adapter.notifyDataSetChanged();
wishEditText.setText("");
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(wishEditText.getWindowToken(), 0);
Toast.makeText(getBaseContext(), "New wish Added To List", Toast.LENGTH_SHORT);
}
});
};
}
Please help me.
When I pressed OK button then my apps has stop but there is no error even eclipse do't show any error.
How I can solve it?
Please help me.
This like inputMethodManager.hideSoftInputFromWindow(wishEditText.getWindowToken(), 0); might be giving you a NullPointerException
Try this way,hope this will help you to solve your problem.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp">
<EditText
android:id="#+id/edtWishText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/btnAddWishText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Add"/>
</LinearLayout>
<ListView
android:id="#+id/lstWish"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="#android:color/white"
android:dividerHeight="1dp"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/txtWishText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txtWishDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"/>
</LinearLayout>
public class MainActivity extends Activity{
private ListView lstWish;
private EditText edtWishText;
private Button btnAddWishText;
private WishListAdapter listAdapter;
private ArrayList<HashMap<String,Object>> wishList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_main);
lstWish = (ListView) findViewById(R.id.lstWish);
edtWishText = (EditText) findViewById(R.id.edtWishText);
btnAddWishText = (Button) findViewById(R.id.btnAddWishText);
wishList =new ArrayList<HashMap<String, Object>>();
listAdapter = new WishListAdapter(this,wishList);
lstWish.setAdapter(listAdapter);
btnAddWishText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtWishText.getText() == null && edtWishText.getText().toString().length()<=0){
edtWishText.setError("Value required");
}else{
HashMap<String,Object> data = new HashMap<String, Object>();
data.put("WishText",edtWishText.getText().toString());
data.put("WishText",new Date());
wishList.add(data);
listAdapter.notifyDataSetChanged();
edtWishText.setText("");
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(edtWishText.getWindowToken(), 0);
Toast.makeText(getBaseContext(), "New wish Added To List", Toast.LENGTH_SHORT).show();
}
}
});
}
class WishListAdapter extends BaseAdapter{
private Context mContext;
public ArrayList<HashMap<String,Object>> wishList;
public WishListAdapter(Context mContext,ArrayList<HashMap<String,Object>> wishList)
{
this.mContext = mContext;
this.wishList = wishList;
}
#Override
public int getCount(){
return wishList.size();
}
#Override
public Object getItem(int position)
{
return wishList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item,null,false);
holder.txtWishText = (TextView) convertView.findViewById(R.id.txtWishText);
holder.txtWishDate = (TextView) convertView.findViewById(R.id.txtWishDate);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.txtWishText.setText(wishList.get(position).get("wishText").toString());
holder.txtWishDate.setText(DateFormat.format("dd/MM/yyyy HH:mm:ss a",(Date)wishList.get(position).get("WishDate")));
return convertView;
}
}
public static class ViewHolder
{
public TextView txtWishText;
public TextView txtWishDate;
}
}

Search functionality Within List View in Android

I'm pretty new to android. I'm trying to develop a search function on a list of items by using arrayadapter as shown below. but search is not working correctly. plz plz help me
Here is my code..
AddToOutlet.java
public class AddToOutlet extends Activity {
SessionManager session;
String success, cus_id, bus_id, cus_outlet;
ArrayList<Item> item;
com.amplio.MyCustomEditText editsearch;
// TextView tvcountoutlet;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtooutlet);
session = new SessionManager(getApplicationContext());
session.checkLoginback();
item = new ArrayList<Item>();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// ID
final String cus_id = user.get(SessionManager.KEY_ID);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("cus_id", cus_id));
String response = null;
try {
response = LoginHttpClient
.executeHttpPost(
"http://10.0.2.2/android_api/add_to_outlet.php",
postParameters);
response = response.toString();
response = response.replaceAll("\\s+", "");
JSONObject json = new JSONObject(response);
JSONArray jArray = json.getJSONArray("customer");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Item it = new Item();
success = json_data.getString("success");
it.setBusname(json_data.getString("bus_name"));
it.setBusid(json_data.getString("bus_id"));
it.setCusId(cus_id);
item.add(it);
}
} catch (Exception e) {
e.printStackTrace();
}
ListView lv = (ListView) findViewById(R.id.list);
final MyAdapter adapter = new MyAdapter(AddToOutlet.this,
R.layout.addtooutlet_list_item, item);
lv.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (com.amplio.MyCustomEditText) findViewById(R.id.EditText01);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
}
Here is MyAdapter.java
public class MyAdapter extends ArrayAdapter<Item> {
ArrayList<Item> item;
LayoutInflater mInflater;
Context context;
private List<Item> item1 = null;
public MyAdapter(Context context, int resource, ArrayList<Item> item) {
super(context, resource, item);
this.item = item;
this.context = context;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return item.size();
}
#Override
public Item getItem(int position) {
return item.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.addtooutlet_list_item,
parent, false);
holder.tv1 = (TextView) convertView.findViewById(R.id.item_bname);
holder.tv2 = (TextView) convertView.findViewById(R.id.item_bid);
holder.tv3 = (TextView) convertView.findViewById(R.id.item_cid);
holder.b = (Button) convertView.findViewById(R.id.item_button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Item it = item.get(position);
holder.tv1.setText(it.getBusname());
holder.tv2.setText(it.getBusid());
holder.tv3.setText(it.getCusId());
holder.b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// String Text1_value = holder.tv1.getText().toString();
// System.out.println(Text1_value);
String bid = holder.tv2.getText().toString();
System.out.println(bid);
String cid = holder.tv3.getText().toString();
System.out.println(cid);
holder.b.setText("Joined");
holder.b.setTextColor(Color.parseColor("#ffffff"));
holder.b.setTextSize(10);
// holder.b.setText("joined");
// Toast.makeText(context, "Join button Clicked",
// Toast.LENGTH_LONG).show();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("cus_id", cid));
postParameters.add(new BasicNameValuePair("bus_id", bid));
String response = null;
try {
response = LoginHttpClient
.executeHttpPost(
"http://10.0.2.2/android_api/update_outlet.php",
postParameters);
String res = response.toString();
res = res.replaceAll("\\s+", "");
int resInt = Integer.parseInt(res);
if (resInt == 1) {
} else {
}
} catch (Exception e) {
}
}
});
return convertView;
}
static class ViewHolder {
Button b;
TextView tv1, tv2, tv3;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
item.clear();
if (charText.length() == 0) {
item.addAll(item);
} else {
for (Item wp : item) {
if (wp.getBusname().toLowerCase(Locale.getDefault())
.contains(charText)) {
item.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Here is Item.java
public class Item {
String busname, busid, cus_id;
public String getBusname() {
return busname;
}
public void setBusname(String busname) {
this.busname = busname;
}
public String getBusid() {
return busid;
}
public void setBusid(String busid) {
this.busid = busid;
}
public String getCusId() {
return cus_id;
}
public void setCusId(String cus_id) {
this.cus_id = cus_id;
}
}
Here is addtooutlet.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical" >
<!-- Editext for Search -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:layout_marginLeft="10dp"
android:background="#ffffff" >
<com.amplio.MyCustomEditText
android:id="#+id/EditText01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="40dp"
android:background="#00000000"
android:ems="20"
android:hint="#string/search"
android:lineSpacingExtra="5dp"
android:textSize="12sp" >
</com.amplio.MyCustomEditText>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#eeeeee" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
</RelativeLayout>
</LinearLayout>
here is my addtooutlet_list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="46dp"
android:background="#ffffff"
android:padding="5dip"
android:weightSum="100" >
<TextView
android:id="#+id/item_bname"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="20"
android:padding="2dp"
android:text="Hello"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textSize="12dip" />
<TextView
android:id="#+id/item_bid"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="20"
android:padding="2dp"
android:text="Hello"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textSize="12dip"
android:visibility="invisible" />
<TextView
android:id="#+id/item_cid"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="20"
android:padding="2dp"
android:text="Hello"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textSize="12dip"
android:visibility="invisible" />
<Button
android:id="#+id/item_button"
android:layout_width="31dp"
android:layout_height="31dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/item_bname"
android:background="#drawable/circle"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="join"
android:textColor="#ffffff"
android:textSize="10sp" />
</RelativeLayout>
Try to do like this. hope it will help you...
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
editsearch.requestFocus();
final ArrayList<Item> itemArray = new ArrayList<Item>();
int textlength = 0;
textlength = editsearch.getText().length();
itemArray.clear();
for (int i = 0; i < item.size(); i++)
{
String itemTitle = item.get(i).name();
String compareItemTitle = "";
if (textlength <= item.length())
{
compareItemTitle = (String) itemTitle.toLowerCase().subSequence(0, textlength);
if(compareItemTitle.contentEquals(editsearch.getText().toString().toLowerCase()))
{
itemArray.add(item.get(i));
}
}
}
adapter = new MyAdapter(AddToOutlet.this, R.layout.addtooutlet_list_item, itemArray);
lv.setAdapter(adapter);
}
}
});
Try this way, this is exactly what you looking for
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
http://androidcss.com/android/android-search-view-php-mysql/
http://androidcss.com/android/fetch-json-data-android/

Parsing Youtube Gdata json into ListView

I have been trying to find a working example of "Parsing Youtube Gdata JSON" in Android to populate a listview.
I have been reading this question, and I almost have it working except for 4 errors..
item_title
item_subtitle
setListAdapter
getListView
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class listview extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//Get the data (see above)
JSONObject json = getJSON.getJSONfromURL("https://gdata.youtube.com/feeds/api/videos?q=random&max-results=50&v=2&alt=jsonc");
try{
final JSONArray array = json.getJSONArray("items");
//Loop the Array
for(int i=0;i < array.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = array.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("title", "" + e.getString("title"));
map.put("viewCount", "Views: " + e.getString("viewCount"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.dubstep,
new String[] { "title", "viewCount" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
//final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(listview.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.listview, menu);
return true;
}
}
It says "Cannot resolve symbol 'item_title' and 'item_subtitle'
and
"Cannot resolve method 'setListAdapter(android.widget.ListAdapter)'
Any help is appreciated, Thanks!
Your activity class does not extend ListActivity. Hence the errors 3 and 4
You should use AsyncTask for network related operation. You cannot run network related operation on the main ui thread.
You should use lazy loading for images. But for sample i have use a ArrayList of bitmaps for thumbnail. You might run into memory leaks. So use lazy loading. Modify the below according to your requirement.
Example:
public class MainActivity extends Activity {
Button b;
ListView lv;
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> title = new ArrayList<String>();
ArrayList<Bitmap> thumb = new ArrayList<Bitmap>();
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.lv);
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Loading..");
b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TheTask().execute();
}
});
}
#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;
}
public void getData()
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?q=random&max-results=50&v=2&alt=jsonc");
// HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");
try
{
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity); // content will be consume only once
JSONObject json = new JSONObject(_response);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title1 = jsonObject.getString("title");
title.add(title1);
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");
URL url1 = new URL(thumbUrl);
Bitmap bmp = BitmapFactory.decodeStream(url1.openConnection().getInputStream());
thumb.add(bmp);
String url;
try {
url = jsonObject.getJSONObject("player").getString("default");
msg.add(url);
} catch (JSONException ignore) {
}
}
}
catch(Exception e1)
{
e1.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
YouTubeAdapter you = new YouTubeAdapter(MainActivity.this,msg,title,thumb);
lv.setAdapter(you);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
getData();
return null;
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/lv"
android:layout_above="#+id/button1"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
YouTubeAdapter
public class YouTubeAdapter extends BaseAdapter{
Context mContext;
Intent intent;
LayoutInflater mInflater;
ArrayList<String> mVideo= new ArrayList<String>();
ArrayList<String> mTitle= new ArrayList<String>();
ArrayList<Bitmap> mThumb= new ArrayList<Bitmap>();
public YouTubeAdapter(Context context,ArrayList<String> a,ArrayList title,ArrayList thumb) {
mContext=context;
mVideo=a;
mTitle = title;
mThumb= thumb;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mVideo.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(final int position, View arg1, ViewGroup arg2) {
ViewHolder vh;
if(arg1==null)
{
arg1=mInflater.inflate(R.layout.video, null);
vh= new ViewHolder();
vh.tv=(TextView)arg1.findViewById(R.id.tvv);
vh.iv=(ImageView)arg1.findViewById(R.id.ivv);
arg1.setTag(vh);
}
else
{
vh= (ViewHolder)arg1.getTag();
}
vh.tv.setText(mTitle.get(position));
vh.iv.setImageBitmap(mThumb.get(position));
return arg1;
}
static class ViewHolder
{
TextView tv;
ImageView iv;
}
}
video.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="vertical"
>
<TextView
android:id="#+id/tvv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000000"
android:textSize="13dp" />
<ImageView
android:id="#+id/ivv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
Snap shot

Categories

Resources