How to handle different events inside ViewPager Tab? - android

I am working on an android project that contains a view pager. The UI of MenuActivity is as following...
Below are the code of view pager activities...
MenuActivity.java
public class MenuActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs;
private String[] category_id;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
CommonFunctions.changeActionBar(getResources(),getActionBar());
// Initialization
initializeFoodCatagories();
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), tabs, category_id, MenuActivity.this);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
//Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
private void initializeFoodCatagories() {
GeneralHelper helper = new GeneralHelper();
JSONObject json = helper.callWebService(getString(R.string.API_END_POINT) + "get_food_category");
String total_items = helper.getValueFromJson(json, "TotalRecords");
tabs = new String[Integer.parseInt(total_items)];
category_id = new String[Integer.parseInt(total_items)];
if(!(total_items.equals("0"))) {
try {
final JSONArray jsonarray = json.getJSONArray("Response");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
tabs[i] = jsonobject.getString("category_name").toString();
category_id[i] = jsonobject.getString("category_id").toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
}}
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
String [] category_name;
String [] category_id;
Activity context;
public TabsPagerAdapter(FragmentManager fm, String[] category_name, String[] category_id, Activity context) {
super(fm);
this.category_name = category_name;
this.category_id = category_id;
this.context = context;
}
#Override
public Fragment getItem(int index) {
for(int i = 0; i < category_name.length; i++) {
if(index==i) {
return new SwipeTabFragment(context, category_id[i]);
}
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return category_name.length;
}}
SwipeTabFragment.java
public class SwipeTabFragment extends Fragment {
Activity context;
ListView list;
private String[] item_name;
private String[] price_per_unit;
private String[] item_image;
private String category_id;
public SwipeTabFragment(Activity context, String category_id) {
this.context = context;
this.category_id = category_id;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_items, container, false);
list = (ListView) rootView.findViewById(R.id.lstItems);
initializeFoodItems(category_id);
list.setAdapter(new ItemListAdapter(context, item_name, price_per_unit));
//ListView event handling
//This event not working
/*list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","ListView activated");
}
});*/
//This event is also not working
/*rootView.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","Plus Image Button activated");
}
});*/
return rootView;
}
private void initializeFoodItems(String position) {
String url = getString(R.string.API_END_POINT) + "get_menu_items?food_cat_id="+position;
GeneralHelper helper = new GeneralHelper();
JSONObject json = helper.callWebService(url);
String total_items = helper.getValueFromJson(json, "TotalRecords");
price_per_unit = new String[Integer.parseInt(total_items)];
item_name = new String[Integer.parseInt(total_items)];
item_image = new String[Integer.parseInt(total_items)];
if(!(total_items.equals("0"))) {
try {
final JSONArray jsonarray = json.getJSONArray("Response");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
price_per_unit[i] = jsonobject.getString("price_per_unit").toString();
item_name[i] = jsonobject.getString("item_name").toString();
item_image[i] = jsonobject.getString("item_image").toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}}
ItemListAdapter.java
public class ItemListAdapter extends ArrayAdapter<String> {
static int grand_total;
private final Activity context;
private final String title[];
private final String price[];
private final String discount[];
public ItemListAdapter(Activity context, String[] title, String[] price, String[] discount) {
super(context, R.layout.item_list, title);
this.context = context;
this.title = title;
this.price = price;
this.discount = discount;
}
#SuppressLint({ "ViewHolder", "InflateParams" })
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View row = inflater.inflate(R.layout.item_list, null,true);
((TextView) row.findViewById(R.id.txtTitl)).setText(title[position]);
final int item_price = Integer.parseInt(price[position]);
((TextView) row.findViewById(R.id.txtPrice)).setText(price[position] + " Rs. Each");
((TextView) row.findViewById(R.id.txtDiscount)).setText(discount[position] + "%");
RatingBar ratingBar = (RatingBar) row.findViewById(R.id.ratingBar);
LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
stars.getDrawable(2).setColorFilter(row.getResources().getColor(R.color.orange), PorterDuff.Mode.SRC_ATOP);
//Increasing Quantity
row.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))+1));
if (Integer.parseInt(qty.getText().toString()) > 0) {
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
//Decreasing Quantity
row.findViewById(R.id.imgMinus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
if (Integer.parseInt(qty.getText().toString()) > 0) {
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))-1));
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
return row;
}
}
activity.menu.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
activity_items.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:orientation="horizontal"
android:background="#drawable/activity_background">
<ListView
android:id="#+id/lstItems"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#drawable/listview_design"/>
</RelativeLayout>
item_list.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="wrap_content"
android:orientation="horizontal"
android:background="#drawable/listview_design"
android:padding="5dp"
android:layout_margin="5dp" >
<TextView
android:id="#+id/txtTitl"
style="#style/ListViewHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="8dp"
android:layout_toRightOf="#+id/imgIcon"
android:gravity="left"
android:text="#string/itemname"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imgIcon"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/img_desp"
android:src="#drawable/food_item_thumb" />
<RatingBar
android:id="#+id/ratingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imgIcon"
android:layout_alignLeft="#+id/imgIcon"
android:background="#80FF0000"
android:numStars="5"
android:paddingBottom="5dp"
android:rating="3.5" />
<TextView
android:id="#+id/txtPrice"
style="#style/ListViewBottomText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtTitl"
android:layout_below="#+id/txtTitl"
android:paddingTop="0dp"
android:text="#string/price_tag"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_alignBottom="#+id/imgIcon"
android:layout_alignLeft="#+id/txtPrice"
android:layout_alignTop="#+id/ratingBar" >
<ImageButton
android:id="#+id/imgPlus"
android:layout_width="25dp"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/sqr_plus"
android:contentDescription="#string/img_desp" />
<ImageButton
android:id="#+id/imgMinus"
android:layout_width="25dp"
android:layout_height="match_parent"
android:layout_alignBottom="#+id/imgPlus"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/sqr_minus"
android:contentDescription="#string/img_desp" />
<TextView
android:id="#+id/txtQty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgPlus"
android:layout_toRightOf="#+id/imgMinus"
android:gravity="center_horizontal|center_vertical"
android:text="#string/qty"
android:textColor="#808080"
android:textSize="20sp" />
<TextView
android:id="#+id/TextView01"
style="#style/ListViewBottomText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center_horizontal|center_vertical"
android:paddingBottom="0dp"
android:paddingTop="0dp"
android:text="#string/total"
android:textColor="#AC2A2E"
android:textSize="20sp" />
</RelativeLayout>
<ImageView
android:id="#+id/imgDiscount"
android:layout_width="30dp"
android:layout_height="40dp"
android:layout_alignRight="#+id/txtTitl"
android:layout_alignTop="#+id/txtTitl"
android:background="#drawable/label"
android:contentDescription="#string/img_desp" />
</RelativeLayout>
I think I've provided sufficient information to understand the problem. GeneralHelper is a web service class to get JSON data from server.
Here I want to get order details by the user. But I am facing some problems as following...
List Items are not clickable, and when I put event handling code, it is not working
How to handle onClick event of ImageButton(imgPlus and (imgMinus) which is placed in ListView item. I tried with the code written in comment in SwipeTabFragment.java, But it is also not working.
Last problem is, Tabs are switching very well when we swipe left or right, but if we click on tabs, then not able to switch.
Please help me to solve above problems or any one of them. Thank You!

How to use LinearLayout:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="400dp" >
<LinearLayout
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</RelativeLayout>
prompts.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type Your Name : "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editTextDialogUserInput"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</LinearLayout>
row.xml
<?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:orientation="vertical" >
<LinearLayout
android:id="#+id/layoutbg"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="#+id/del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REMOVE" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
MainActivity.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.bean.FriendBean;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private LinearLayout mList;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
int loader = R.drawable.loader;
int i;
String val;
// public LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (LinearLayout) findViewById(R.id.layout1);
final ImageLoader img = new ImageLoader(getApplicationContext());
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsonarray.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject obj = new JSONObject(myjsonstring);
JSONArray jsonarray = obj.getJSONArray("json");
Log.e("Length", "" + jsonarray.length());
for (i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
String friend_name = jsonObj.getString("friend_name");
String friend_phone = jsonObj.getString("friend_phone");
String url = jsonObj.getString("image_url");
FriendBean bean = new FriendBean(url, friend_name, friend_phone);
arr.add(bean);
Log.e("u", url);
Log.e("friend_name", friend_name);
Log.e("friend_phone", friend_phone);
LayoutInflater vi = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View v = vi.inflate(R.layout.row, null);
final ImageView im = (ImageView) v.findViewById(R.id.img);
final TextView t1 = (TextView) v.findViewById(R.id.name);
final TextView t2 = (TextView) v.findViewById(R.id.num);
final Button del = (Button) v.findViewById(R.id.del);
img.DisplayImage(url, loader, im);
t1.setText(friend_name);
t2.setText(String.valueOf(i));
mList.addView(v);
t1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
userInput.setText(t1.getText().toString());
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to
// result
// edit text
int f = Integer.parseInt(t2.getText()
.toString());
Toast.makeText(getApplicationContext(),
"Position " + f, Toast.LENGTH_SHORT)
.show();
val = userInput.getText().toString();
Toast.makeText(getApplicationContext(),
val, Toast.LENGTH_SHORT).show();
t1.setText(val);
// mList.addView(v1);
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated
// method
// stub
Toast.makeText(
getApplicationContext(),
"Previously "
+ mList.getChildCount(),
Toast.LENGTH_SHORT).show();
int f = Integer.parseInt(t2.getText()
.toString());
mList.removeViewAt(f);
Toast.makeText(
getApplicationContext(),
"Position "
+ t1.getText().toString(),
Toast.LENGTH_SHORT).show();
myFunction(mList);
}
});
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Log.e("MSG", "HI");
}
});
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Previously " + mList.getChildCount(),
Toast.LENGTH_SHORT).show();
int f = Integer.parseInt(t2.getText().toString());
mList.removeViewAt(f);
Toast.makeText(getApplicationContext(), "Position " + f,
Toast.LENGTH_SHORT).show();
myFunction(mList);
}
});
im.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
t1.getText().toString(), Toast.LENGTH_SHORT).show();
return false;
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void myFunction(LinearLayout l) {
LayoutInflater vi = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.row, null);
int c = l.getChildCount();
for (int j = 0; j < c; j++) {
v = l.getChildAt(j);
TextView t2 = (TextView) v.findViewById(R.id.num);
t2.setText(String.valueOf(j));
}
Toast.makeText(getApplicationContext(), "Finally " + c,
Toast.LENGTH_SHORT).show();
}
}
jsonarray.json (put this on assets folder)
{ "json" : [ { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Madhumoy",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sattik",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Koushik",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Himanshu",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sandy",
"friend_phone" : "123"
}
] }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.customlist"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.customlist.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
FriendBean.java
public class FriendBean {
private String Image;
private String name;
private String ph;
public FriendBean(String Image,String name,String ph){
this.Image = Image;
this.name = name;
this.ph = ph;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPh() {
return ph;
}
public void setPh(String ph) {
this.ph = ph;
}
}
Just avoid the ImageLoader class. I expect that you can show a image from an URL. If you can do that then just use your method to show a image from an URL to the im ImageView...
Just create a new project with this files and you will understand this..

You have intentionally commented ListView's onItemclicklistener inside your onCreateView
Uncomment the code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_items, container, false);
list = (ListView) rootView.findViewById(R.id.lstItems);
initializeFoodItems(category_id);
list.setAdapter(new ItemListAdapter(context, item_name, price_per_unit));
//ListView event handling
list.setOnItemClickListener(itemClickListener );
return rootView;
}
ImageVIew Click
Write this method anywhere
// Item Click Listener for the listview
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
RelativeLayout linearLayoutParent = (RelativeLayout ) container;
// Getting the inner Linear Layout
RelativeLayout linearLayoutChild = (RelativeLayout ) linearLayoutParent.getChildAt(1);
// Getting the Country TextView
ImageView iv = (ImageView) linearLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), "Image CLicked", Toast.LENGTH_SHORT).show();
}
};

I got solution of two problems. That are...
How to handle onClick event of ImageButton(imgPlus and imgMinus) which is placed in ListView item. I tried with the code written in comment in SwipeTabFragment.java, But it is also not working.
Solution :
I am handling onclick event in ItemListAdapter.java that is working fine. Below is the code of this file. That may be helpful for others.
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
public class ItemListAdapter extends ArrayAdapter<String> {
static int grand_total;
private final Activity context;
private final String title[];
private final String price[];
private final String discount[];
public ItemListAdapter(Activity context, String[] title, String[] price, String[] discount) {
super(context, R.layout.item_list, title);
this.context = context;
this.title = title;
this.price = price;
this.discount = discount;
}
#SuppressLint({ "ViewHolder", "InflateParams" })
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View row = inflater.inflate(R.layout.item_list, null,true);
((TextView) row.findViewById(R.id.txtTitl)).setText(title[position]);
final int item_price = Integer.parseInt(price[position]);
((TextView) row.findViewById(R.id.txtPrice)).setText(price[position] + " Rs. Each");
((TextView) row.findViewById(R.id.txtDiscount)).setText(discount[position] + "%");
RatingBar ratingBar = (RatingBar) row.findViewById(R.id.ratingBar);
LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
stars.getDrawable(2).setColorFilter(row.getResources().getColor(R.color.orange), PorterDuff.Mode.SRC_ATOP);
//Increasing Quantity
row.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))+1));
if (Integer.parseInt(qty.getText().toString()) > 0) {
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
//Decreasing Quantity
row.findViewById(R.id.imgMinus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
if (Integer.parseInt(qty.getText().toString()) > 0) {
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))-1));
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
return row;
}
}
Tabs are switching very well when we swipe left or right, but if we click on tabs, then not able to switch.
Solution : I simply put the following line in the onTabSelected() and make the tabs working. This was suggested by #AvishekDas. Again Thanks for this.
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
But I'm still finding problem 1. My listView is not clickable. If any of you have solution then please post. Thank you!

Related

listview position value not exceeding 5

I have used a custom adapter to populate list view which is populating correctly using data. I have some textview which is getting data from database. when i click update it should get data from textview and present it to edittext for correction or updation. but it is not working correctly. Click on update some time enable more that two rows for updation and also data change from the original one.
Please help to correct this
UpdatePathi.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.app.nirvachan.rssb.UpdatePathiActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorHead"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Pathi ID"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Pathi Name"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Center ID"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Point ID"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Contact No"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.1"
android:text="Options"
android:padding="5dip"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listpathi"></ListView>
</LinearLayout>
Custom_Pathi_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="wrap_content"
android:background="#color/colorList"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layoutEdit"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtPathiID"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtPathiName"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtCenterID"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtPointID"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtContactNo"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1.1">
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/btnEdit"
android:layout_weight="1"
android:src="#mipmap/ic_edit"
android:textAllCaps="false"
android:background="#android:color/transparent"/>
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/btnDelete"
android:layout_weight="1"
android:src="#mipmap/ic_delete"
android:text="Delete"
android:textAllCaps="false"
android:background="#android:color/transparent"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layoutUpdate"
android:visibility="gone"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/etPathiID"
android:layout_weight="1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/etPathiName"
android:textSize="10sp"
android:inputType="textPersonName"
android:layout_weight="1"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/etCenterID"
android:layout_weight="1"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/etPointID"
android:layout_weight="1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="number"
android:id="#+id/etContactNo"
android:textSize="10sp"
android:layout_weight="1"/>
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/btnUpdate"
android:src="#mipmap/ic_update"
android:layout_weight="1.1"
android:textAllCaps="false"
android:background="#android:color/transparent"/>
</LinearLayout>
</LinearLayout>
UpdatePathiActivity.java
package com.app.nirvachan.rssb;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class UpdatePathiActivity extends AppCompatActivity {
ListView listPathi;
JSONParser jsonParser = new JSONParser();
String pathiID, pathiName, contactNo;
int centerID, pointID;
private static String url_get_pathi = "http://onkararts.000webhostapp.com/php/rssb_get_pathi.php";
private static String url_get_point = "http://onkararts.000webhostapp.com/php/rssb_get_point.php";
private static String url_get_center = "http://onkararts.000webhostapp.com/php/rssb_get_center.php";
private static String url_update_pathi = "http://onkararts.000webhostapp.com/php/rssb_update_pathi.php";
private static String url_delete_pathi = "http://onkararts.000webhostapp.com/php/rssb_delete_pathi.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PATHIS = "pathis";
private static final String TAG_CENTERS = "centers";
private static final String TAG_POINTS = "points";
private static final String TAG_POINT_ID = "Point_ID";
private static final String TAG_POINT_NAME = "Point_Name";
private static final String TAG_CENTER_ID = "Center_ID";
private static final String TAG_CENTER_NAME = "Center_Name";
private static final String TAG_PATHI_ID = "Pathi_ID";
private static final String TAG_PATHI_NAME = "Pathi_Name";
private static final String TAG_CONTACT_NO = "Contact_No";
ArrayList<Pathi> pathi_Data;
UpdatePathiActivity.PathiAdapter a_pathi;
User[] centers_data, points_data;
SpinAdapter a_centers, a_points;
JSONArray centers, points, pathis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_pathi);
listPathi = (ListView) findViewById(R.id.listpathi);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
UpdatePathiActivity.getCenters gc = new UpdatePathiActivity.getCenters();
gc.execute();
UpdatePathiActivity.getPoints gp = new UpdatePathiActivity.getPoints();
gp.execute();
UpdatePathiActivity.getPathis gr = new UpdatePathiActivity.getPathis();
gr.execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
public class getPathis extends AsyncTask<String, String, ArrayList<Pathi>> {
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(ArrayList<Pathi> pathis) {
a_pathi = new UpdatePathiActivity.PathiAdapter(UpdatePathiActivity.this, pathis);
listPathi.setAdapter(a_pathi);
}
#Override
protected ArrayList<Pathi> doInBackground(String... args) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(
url_get_pathi, "GET", params);
Log.d("Getting Result", json.toString());
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// vehicles found
// Getting Array of vehicles
pathis = json.getJSONArray(TAG_PATHIS);
pathi_Data = new ArrayList<Pathi>();
for (int i = 0; i < pathis.length(); i++) {
JSONObject c = pathis.getJSONObject(i);
Pathi r = new Pathi(Integer.parseInt(c.getString(TAG_PATHI_ID)), c.getString(TAG_PATHI_NAME), Integer.parseInt(c.getString(TAG_CENTER_ID)), Integer.parseInt(c.getString(TAG_POINT_ID)), Long.parseLong(c.getString(TAG_CONTACT_NO)));
pathi_Data.add(i,r);
}
} else {
}
} catch (JSONException ex) {
ex.getMessage().toString();
}
return pathi_Data;
}
}
public class updatePathi extends AsyncTask<String, String, String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(getBaseContext(),r,Toast.LENGTH_SHORT).show();
if(isSuccess) {
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Pathi_ID", pathiID));
params.add(new BasicNameValuePair("Pathi_Name", pathiName));
params.add(new BasicNameValuePair("Center_ID", centerID+""));
params.add(new BasicNameValuePair("Point_ID", pointID+""));
params.add(new BasicNameValuePair("Contact_No", contactNo));
JSONObject json = jsonParser.makeHttpRequest(url_update_pathi,"POST", params);
Log.d("Create Response", json.toString());
try {
int r = json.getInt(TAG_SUCCESS);
if(r == 1){
z = "Record Updated Successfully";
isSuccess = true;
}
else{
isSuccess = false;
z = "Pathi Updation Failed";
}
}
catch (JSONException ex) {
z = ex.getMessage();
}
return z;
}
}
public class deletePathi extends AsyncTask<String, String, String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(getBaseContext(),r,Toast.LENGTH_SHORT).show();
if(isSuccess) {
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Pathi_ID", pathiID));
JSONObject json = jsonParser.makeHttpRequest(url_delete_pathi,"POST", params);
Log.d("Create Response", json.toString());
try {
int r = json.getInt(TAG_SUCCESS);
if(r == 1){
z = "Record Deleted Successfully";
isSuccess = true;
}
else{
isSuccess = false;
z = "Pathi deletion Failed";
}
}
catch (JSONException ex) {
z = ex.getMessage();
}
return z;
}
}
public class PathiAdapter extends BaseAdapter {
Context context;
List<Pathi> pathiList;
public PathiAdapter(Context context, List<Pathi> pathiList) {
this.context = context;
this.pathiList = pathiList;
}
#Override
public int getCount() {
return pathiList.size();
}
#Override
public Pathi getItem(int position) {
return pathiList.get(position);
}
#Override
public long getItemId(int position) {
return pathiList.indexOf(getItem(position));
}
private class ViewHolder{
LinearLayout l_edit;
TextView t_pathiID;
TextView t_pathiName;
TextView t_centerID;
TextView t_pointID;
TextView t_contactNo;
ImageButton b_edit;
ImageButton b_delete;
LinearLayout l_update;
TextView e_pathiID;
EditText e_pathiName;
Spinner e_centerID;
Spinner e_pointID;
EditText e_contactNo;
ImageButton b_update;
}
UpdatePathiActivity.PathiAdapter.ViewHolder d_holder = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_pathi_item, null);
d_holder = new UpdatePathiActivity.PathiAdapter.ViewHolder();
d_holder.t_pathiID = (TextView) convertView.findViewById(R.id.txtPathiID);
d_holder.t_pathiName = (TextView) convertView.findViewById(R.id.txtPathiName);
d_holder.t_contactNo = (TextView) convertView.findViewById(R.id.txtContactNo);
d_holder.t_centerID = (TextView) convertView.findViewById(R.id.txtCenterID);
d_holder.t_pointID = (TextView) convertView.findViewById(R.id.txtPointID);
d_holder.b_edit = (ImageButton) convertView.findViewById(R.id.btnEdit);
d_holder.b_delete = (ImageButton) convertView.findViewById(R.id.btnDelete);
d_holder.l_edit = (LinearLayout) convertView.findViewById(R.id.layoutEdit);
d_holder.l_update = (LinearLayout) convertView.findViewById(R.id.layoutUpdate);
d_holder.e_pathiID = (TextView) convertView.findViewById(R.id.etPathiID);
d_holder.e_pathiName = (EditText) convertView.findViewById(R.id.etPathiName);
d_holder.e_contactNo = (EditText) convertView.findViewById(R.id.etContactNo);
d_holder.e_centerID = (Spinner) convertView.findViewById(R.id.etCenterID);
d_holder.e_pointID = (Spinner) convertView.findViewById(R.id.etPointID);
d_holder.b_update = (ImageButton) convertView.findViewById(R.id.btnUpdate);
convertView.setTag(d_holder);
}
else{
d_holder = (UpdatePathiActivity.PathiAdapter.ViewHolder) convertView.getTag();
}
Pathi row_pos = pathiList.get(position);
d_holder.t_pathiID.setText(String.valueOf(row_pos.getPathiID()));
d_holder.t_pathiName.setText(row_pos.getPathiName());
d_holder.t_contactNo.setText(String.valueOf(row_pos.getContactNo()));
d_holder.t_centerID.setText(String.valueOf(row_pos.getCenterID()));
d_holder.t_pointID.setText(String.valueOf(row_pos.getPointID()));
d_holder.b_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = listPathi.getChildAt(position);
TextView u_pathiID = (TextView) view.findViewById(R.id.etPathiID);
EditText u_pathiName = (EditText) view.findViewById(R.id.etPathiName);
EditText u_contactNo = (EditText) view.findViewById(R.id.etContactNo);
Spinner u_centerID = (Spinner) view.findViewById(R.id.etCenterID);
Spinner u_pointID = (Spinner) view.findViewById(R.id.etPointID);
LinearLayout u_edit = (LinearLayout) view.findViewById(R.id.layoutEdit);
LinearLayout u_update = (LinearLayout) view.findViewById(R.id.layoutUpdate);
Pathi pathi = getItem(position);
u_pathiID.setText(String.valueOf(pathi.getPointID()));
u_pathiName.setText(pathi.getPathiName());
u_contactNo.setText(String.valueOf(pathi.getContactNo()));
u_centerID.setAdapter(a_centers);
u_centerID.setSelection(pathi.getCenterID());
u_pointID.setAdapter(a_points);
u_pointID.setSelection(pathi.getPointID());
u_edit.setVisibility(View.GONE);
u_update.setVisibility(View.VISIBLE);
}
});
d_holder.b_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = listPathi.getChildAt(position);
TextView u_pathiID = (TextView) view.findViewById(R.id.etPathiID);
EditText u_pathiName = (EditText) view.findViewById(R.id.etPathiName);
EditText u_contactNo = (EditText) view.findViewById(R.id.etContactNo);
Spinner u_centerID = (Spinner) view.findViewById(R.id.etCenterID);
Spinner u_pointID = (Spinner) view.findViewById(R.id.etPointID);
pathiID = u_pathiID.getText().toString();
pathiName = u_pathiName.getText().toString();
contactNo = u_contactNo.getText().toString();
centerID = a_centers.getItem(u_centerID.getSelectedItemPosition()).getId();
pointID = a_centers.getItem(u_pointID.getSelectedItemPosition()).getId();
UpdatePathiActivity.updatePathi ur = new UpdatePathiActivity.updatePathi();
ur.execute();
}
});
d_holder.b_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pathi row_pos = pathiList.get(position);
pathiID = String.valueOf(row_pos.getPathiID());
//Toast.makeText(UpdateCenterActivity.this, centerID+centerName+address+contactNo+eMailID+secretaryName+secretaryNo, Toast.LENGTH_LONG).show();
UpdatePathiActivity.deletePathi dr = new UpdatePathiActivity.deletePathi();
dr.execute();
}
});
return convertView;
}
}
public class getCenters extends AsyncTask<String, String, User[]> {
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(User[] centers) {
a_centers = new SpinAdapter(getBaseContext(), android.R.layout.simple_spinner_item, centers);
}
#Override
protected User[] doInBackground(String... args) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(
url_get_center, "GET", params);
Log.d("Getting Result", json.toString());
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// vehicles found
// Getting Array of vehicles
centers = json.getJSONArray(TAG_CENTERS);
centers_data = new User[centers.length()+1];
// looping through All Vehicles
centers_data[0] = new User();
centers_data[0].setId(0);
centers_data[0].setName("Please Select Center Name");
for (int i = 0; i < centers.length(); i++) {
JSONObject c = centers.getJSONObject(i);
centers_data[i+1] = new User();
centers_data[i+1].setId(c.getInt(TAG_CENTER_ID));
centers_data[i+1].setName(c.getString(TAG_CENTER_NAME));
}
} else {
}
} catch (JSONException ex) {
ex.getMessage().toString();
}
return centers_data;
}
}
public class getPoints extends AsyncTask<String, String, User[]> {
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(User[] points) {
a_points = new SpinAdapter(getBaseContext(), android.R.layout.simple_spinner_item, points);
}
#Override
protected User[] doInBackground(String... args) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(
url_get_point, "GET", params);
Log.d("Getting Result", json.toString());
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// vehicles found
// Getting Array of vehicles
points = json.getJSONArray(TAG_POINTS);
points_data = new User[points.length()+1];
points_data[0] = new User();
points_data[0].setId(0);
points_data[0].setName("Please Select Point Name");
for (int i = 0; i < points.length(); i++) {
JSONObject c = points.getJSONObject(i);
points_data[i+1] = new User();
points_data[i+1].setId(c.getInt(TAG_POINT_ID));
points_data[i+1].setName(c.getString(TAG_POINT_NAME));
}
} else {
}
} catch (JSONException ex) {
ex.getMessage().toString();
}
return points_data;
}
}
}
Please find screenshot of the problem
Here when I click on 6th item
Here when I click on 7th item
Modify your code, your onClickListener should be outside if else block
public class PathiAdapter extends BaseAdapter {
Context context;
List<Pathi> pathiList;
public PathiAdapter(Context context, List<Pathi> pathiList) {
this.context = context;
this.pathiList = pathiList;
}
#Override
public int getCount() {
return pathiList.size();
}
#Override
public Pathi getItem(int position) {
return pathiList.get(position);
}
#Override
public long getItemId(int position) {
return pathiList.indexOf(getItem(position));
}
private class ViewHolder{
LinearLayout l_edit;
TextView t_pathiID;
TextView t_pathiName;
TextView t_centerID;
TextView t_pointID;
TextView t_contactNo;
ImageButton b_edit;
ImageButton b_delete;
LinearLayout l_update;
TextView e_pathiID;
EditText e_pathiName;
Spinner e_centerID;
Spinner e_pointID;
EditText e_contactNo;
ImageButton b_update;
}
UpdatePathiActivity.PathiAdapter.ViewHolder d_holder = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_pathi_item, null);
d_holder = new UpdatePathiActivity.PathiAdapter.ViewHolder();
d_holder.t_pathiID = (TextView) convertView.findViewById(R.id.txtPathiID);
d_holder.t_pathiName = (TextView) convertView.findViewById(R.id.txtPathiName);
d_holder.t_contactNo = (TextView) convertView.findViewById(R.id.txtContactNo);
d_holder.t_centerID = (TextView) convertView.findViewById(R.id.txtCenterID);
d_holder.t_pointID = (TextView) convertView.findViewById(R.id.txtPointID);
d_holder.b_edit = (ImageButton) convertView.findViewById(R.id.btnEdit);
d_holder.b_delete = (ImageButton) convertView.findViewById(R.id.btnDelete);
d_holder.l_edit = (LinearLayout) convertView.findViewById(R.id.layoutEdit);
d_holder.l_update = (LinearLayout) convertView.findViewById(R.id.layoutUpdate);
d_holder.e_pathiID = (TextView) convertView.findViewById(R.id.etPathiID);
d_holder.e_pathiName = (EditText) convertView.findViewById(R.id.etPathiName);
d_holder.e_contactNo = (EditText) convertView.findViewById(R.id.etContactNo);
d_holder.e_centerID = (Spinner) convertView.findViewById(R.id.etCenterID);
d_holder.e_pointID = (Spinner) convertView.findViewById(R.id.etPointID);
d_holder.b_update = (ImageButton) convertView.findViewById(R.id.btnUpdate);
convertView.setTag(d_holder);
}
else{
d_holder = (UpdatePathiActivity.PathiAdapter.ViewHolder) convertView.getTag();
}
d_holder.b_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicked at :" +position, Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
just chnge this code in your getView
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_pathi_item, null);
d_holder = new UpdatePathiActivity.PathiAdapter.ViewHolder();
d_holder.t_pathiID = (TextView) convertView.findViewById(R.id.txtPathiID);
d_holder.t_pathiName = (TextView) convertView.findViewById(R.id.txtPathiName);
d_holder.t_contactNo = (TextView) convertView.findViewById(R.id.txtContactNo);
d_holder.t_centerID = (TextView) convertView.findViewById(R.id.txtCenterID);
d_holder.t_pointID = (TextView) convertView.findViewById(R.id.txtPointID);
d_holder.b_edit = (ImageButton) convertView.findViewById(R.id.btnEdit);
d_holder.b_delete = (ImageButton) convertView.findViewById(R.id.btnDelete);
d_holder.l_edit = (LinearLayout) convertView.findViewById(R.id.layoutEdit);
d_holder.l_update = (LinearLayout) convertView.findViewById(R.id.layoutUpdate);
d_holder.e_pathiID = (TextView) convertView.findViewById(R.id.etPathiID);
d_holder.e_pathiName = (EditText) convertView.findViewById(R.id.etPathiName);
d_holder.e_contactNo = (EditText) convertView.findViewById(R.id.etContactNo);
d_holder.e_centerID = (Spinner) convertView.findViewById(R.id.etCenterID);
d_holder.e_pointID = (Spinner) convertView.findViewById(R.id.etPointID);
d_holder.b_update = (ImageButton) convertView.findViewById(R.id.btnUpdate);
convertView.setTag(d_holder);
}
else{
d_holder = (UpdatePathiActivity.PathiAdapter.ViewHolder) convertView.getTag();
}
d_holder.b_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicked at :" +position, Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
Make Your Listview's onClickListener outside of the if and else
if()
{
}
else
{
}
d_holder.b_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicked at :" +position, Toast.LENGTH_SHORT).show();
}
});

I am new in android,i want to delete a row on clicking delete button that are shown in front of each row in list view

This is may XML class random values in which we make a row that I want to delete
randomvalues.xml
<LinearLayout
android:id="#+id/linear"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/addbtn">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/img1"
/>
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/adress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageButton
android:id="#+id/removebtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/remove"/>
</LinearLayout>
</LinearLayout>
this is my activity_main XML in which i used a list view to show a row that I make in random values XML file
activity_main.xml
<?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="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="com.example.chaqeel.taskviews.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear">
<ImageButton
android:id="#+id/addbtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/add"
android:layout_marginLeft="280dp"/>
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linear"
>
</ListView>
</RelativeLayout>
This is MainActivity.java in which we used a array to show the values
MainActivity.java
package com.example.chaqeel.taskviews;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.img1, R.drawable.img2, R.drawable.img3,
R.drawable.img4, R.drawable.img5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new dataListAdapter(Names, Address, Images));
}
class dataListAdapter extends BaseAdapter {
String[] Name, Addres;
int[] imge;
/*dataListAdapter() {
Name = null;
Addres = null;
imge=null;
}*/
public dataListAdapter(String[] text, String[] text1, int[] text3) {
Name = text;
Addres = text1;
imge = text3;
}
public int getCount() {
return Name.length;
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomvalues, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(Names[position]);
Addres.setText(Address[position]);
imge.setImageResource(Images[position]);
final ArrayList<String> lvv= new ArrayList<>();
Collections.addAll(lvv,Names);
// Collection.addAll(lvv,Address);
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
lvv.remove(Names);
lvv.remove(Address);
notifyDataSetChanged();
}
});
return (row);
}
}
}
In the onClickListener try the following code
youradapter.notifyDataSetChanged();
In the deletebutton onClickListener try this
Names = ArrayUtils.removeElement(Names,Names[position]);
Address = ArrayUtils.removeElement(Address,Address[position]);
notifyDataSetChanged();
Though it is advised to use OOP concept like a class to hold the Arrays of Names,Address and Images.
Try below code:
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Name = ArrayUtils.removeElement(Names, Names[position]);
Address = ArrayUtils.removeElement(Address, Address[position]);
imge = ArrayUtils.removeElement(imge, imge[position]);
notifyDataSetChanged();
}
});
change this:
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setTag(position);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer index = (Integer) view.getTag();
lvv.remove(index.intValue());
notifyDataSetChanged();
}
});
Are you from Chakwal? I am Chakwalian. Again StackOverflow is telling me that my answer does not meet thier quality requirements.
You need to better idea to use Model class as below:-
create a model class MyModel.class
import java.util.ArrayList;
import java.util.List;
public class MyModel {
String Name, Address;
int image;
public MyModel(String name, String address, int image) {
Name = name;
Address = address;
this.image = image;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
public int getImage() {
return image;
}
}
and then add with adapter class see below:
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.ic_menu_camera, R.drawable.ic_menu_gallery, R.drawable.ic_menu_manage,
R.drawable.ic_menu_send, R.drawable.ic_menu_share};
private List<MyModel> myModel=new ArrayList<>();
private DataListAdapter dataListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
lv = (ListView) findViewById(R.id.listview);
for(int i=0;i<Names.length;i++){
myModel.add( new MyModel(Names[i],Address[i],Images[i]));
}
dataListAdapter=new DataListAdapter(myModel);
lv.setAdapter(dataListAdapter);
}
class DataListAdapter extends BaseAdapter {
private List<MyModel> myModel=new ArrayList<>();
public DataListAdapter(List<MyModel> myModel) {
this.myModel=myModel;
}
public int getCount() {
return myModel.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomevalue, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(myModel.get(position).getName());
Addres.setText(myModel.get(position).getAddress());
imge.setImageResource(myModel.get(position).getImage());
ImageButton dltbutton = (ImageButton) row.findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myModel.remove(position);
notifyDataSetChanged();
}
});
return (row);
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
add android:onClick="addMore" to your add button
it will fine Happy Coding :)
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info =(AdapterContextMenuInfo) item.getMenuInfo();
pos=info.position;
deleteditem=myList.get(pos);
if(item.getTitle()=="Delete")
{
String delete = myList.get(pos);
File f = new File(path + "/"+ delete);
if (f != null && f.exists())
{
f.delete();
}
myList.remove(pos);
adapter. notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "item has deleted",Toast.LENGTH_LONG).show();
}

Set height on dynamic listview item

I am new to Android Development and I am having trouble with designing. I am trying to make an SMS app. I was successful in accessing the inbox and displaying the contact names. Now I want to set a custom height on each listview-item and remove the divider height which looks like a bottom border.
android:minHeight doesn't seem to work in my case. I also want to add click event on each dynamically created listview-item but it doesn't seem to work.
Here is my code:
MainActivity.java
public class MainActivity extends ListActivity {
ArrayList<String> messages = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayList<String> msglist = new ArrayList<String>();
String num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView lvmsgs = (ListView) findViewById(R.id.msglist);
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null, null);
String sms = null;
ContentResolver resolver = null;
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(cur.getColumnIndexOrThrow("body")) + "\n";
num = cur.getString(2);
num = num.replace("+639", "09");
if (msglist.contains(num)) {
} else {
msglist.add(num);
messages.add(getContactName(num).toString());
}
}
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, messages);
setListAdapter(adapter);
lvmsgs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Toast",
Toast.LENGTH_LONG).show();
}
});
}
private String getContactName(String number) {
String name = null;
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
} else {
return number;
}
return name;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
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:id="#+id/msglist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false" />
</RelativeLayout>
I think you can pass your own layout to arrayadapter .Create a layout with only text view without any layout. And set height and padding to text view.
activity_main:
<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:id="#+id/lvCustomList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
layout_list_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:id="#+id/ivIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/start1" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Title" />
<TextView
android:id="#+id/tvDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Description" />
</LinearLayout>
</LinearLayout>
ModelClass:
package com.example.evuser.customlistviewdemo;
public class ListData {
String Description;
String title;
int imgResId;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
MainActivity:
package com.example.evuser.customlistviewdemo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
ListView lvDetail;
Context context = MainActivity.this;
ArrayList<ListData> myList = new ArrayList<ListData>();
String[] title = new String[]{
"Title 1", "Title 2", "Title 3", "Title 4",
"Title 5", "Title 6", "Title 7", "Title 8"
};
String[] desc = new String[]{
"Desc 1", "Desc 2", "Desc 3", "Desc 4",
"Desc 5", "Desc 6", "Desc 7", "Desc 8"
};
int[] img = new int[]{
R.drawable.start1, R.drawable.star2, R.drawable.star3, R.drawable.star4,
R.drawable.star5, R.drawable.star4, R.drawable.star7, R.drawable.star8
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvDetail = (ListView) findViewById(R.id.lvCustomList);
// insert data into the list before setting the adapter
// otherwise it will generate NullPointerException - Obviously
getDataInList();
lvDetail.setAdapter(new MyBaseAdapter(context, myList));
}
private void getDataInList() {
for (int i = 0; i < title.length; i++) {
// Create a new object for each list item
ListData ld = new ListData();
ld.setTitle(title[i]);
ld.setDescription(desc[i]);
ld.setImgResId(img[i]);
// Add this object into the ArrayList myList
myList.add(ld);
}
}
}
AdapterClass:
package com.example.evuser.customlistviewdemo;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class MyBaseAdapter extends BaseAdapter {
ArrayList<ListData> myList = new ArrayList<ListData>();
LayoutInflater inflater;
Context context;
public MyBaseAdapter(Context context, ArrayList<ListData> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public ListData getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_list_item, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
ListData currentListData = getItem(position);
mViewHolder.tvTitle.setText(currentListData.getTitle());
mViewHolder.tvDesc.setText(currentListData.getDescription());
mViewHolder.ivIcon.setImageResource(currentListData.getImgResId());
return convertView;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
tvDesc = (TextView) item.findViewById(R.id.tvDesc);
ivIcon = (ImageView) item.findViewById(R.id.ivIcon);
}
}
}
In the above example, I have given how to create custom layout for listview and use that in adapter class. You modify this class according to your requirement.

ListFragment and Custom Adapter Issue

Two issue with List Fragment: 1. I have a class that extends ListFragments.In the onCreated, I am setting my custom Adapter. The issue is that when the user logs in, the adadpter is null and would not have a value until the user searches for an owner. As a result, it throws an exception when it tries to set up the listadapter and it finds the ArrayAdapter object to be null. I have a custome layout that has a listview and a textview, but I still gets the error. See sample code below. I bold the line of code where the issue happens. Also, I bold few other section where I think it may be important to notice.
I implemented Parcelable in the class "Owner" so that I can pass the object as a ParcelableArray. Even though the object is not null, retrieving it in the OwnerDetail class shows null as if I did not pass it it. I've seen several example, but I am not able to get it right. What am I doing wrong here?
Note: If I were to call the AsyncTask in the OwnerDetail class and set the ListAdapter, it will work fine. The issue with that is that it will display a list of owners as soon as the user is logged in which is not the expected behavior. The behavior that I want is to login first, search for an owner, display the owner, double click on an owner, and finally display a list of cars that the owner owns. I am doing this project, so I can learn how to use ListFraments.
// Here is the entire code
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Car implements Parcelable {
private String _make;
private String _model;
private String _year;
public Car()
{
this._make = "";
this._model = "";
this._year = "";
}
public Car(String make)
{
this._make = make;
}
public Car(String make, String year)
{
this._make = make;
this._year = year;
}
public Car(String make, String model, String year)
{
this._make = make;
this._model = model;
this._year = year;
}
//Getters
public String getMake()
{
return _make;
}
public String getModel()
{
return _model;
}
public String getYear()
{
return _year;
}
//Setters
public void setMake(String make)
{
_make = make;
}
public void setModel(String model)
{
_model = model;
}
public void setYear(String year)
{
_year = year;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CarDetail extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
String[] myCars = {};
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> carAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, myCars);
setListAdapter(carAdapter);
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Login extends Activity implements OnClickListener{
private Button btnLogin;
private EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initializeVariables();
}
public void initializeVariables()
{
btnLogin = (Button) this.findViewById(R.id.bLogin);
etUsername = (EditText)this.findViewById(R.id.etUserName);
etPassword = (EditText)this.findViewById(R.id.etPassword);
btnLogin.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
Log.i("Tag", "In Onclick Litener");
String uName = etUsername.getText().toString();
String pWord = etPassword.getText().toString();
if(uName.equals("owner") && pWord.equals("1234"))
{
Log.i("Tag", "username =" + uName + "Password =" + pWord);
Intent intent = new Intent(this, People.class);
startActivity(intent);
}
}
}
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Owner implements Parcelable {
private String _firstName;
private String _lastName;
private String _carId;
private Car _car;
public Owner()
{
this._firstName = "";
this._lastName = "";
this._carId = "";
}
public Owner(String lName)
{
this._lastName = lName;
}
public Owner(String lName, String cId)
{
this._lastName = lName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId, Car car)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
this._car = car;
}
//Getters
public String getFirstName()
{
return _firstName;
}
public String getLastName()
{
return _lastName;
}
public String getCarId()
{
return _carId;
}
public Car getCar()
{
return _car;
}
//Setters
public void setFirstName(String fName)
{
_firstName = fName;
}
public void setLastName(String lName)
{
_lastName = lName;
}
public void setCarId(String cId)
{
_carId = cId;
}
public void setCar(Car car)
{
_car = car;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(_firstName);
dest.writeString(_lastName);
dest.writeString(_carId);
dest.writeParcelable(_car, flags);
}
public Owner(Parcel source){
_firstName = source.readString();
_lastName = source.readString();
_carId = source.readString();
_car = source.readParcelable(Car.class.getClassLoader());
}
public class MyCreator implements Parcelable.Creator<Owner> {
public Owner createFromParcel(Parcel source) {
return new Owner(source);
}
public Owner[] newArray(int size) {
return new Owner[size];
}
}
}
package com.mb.carlovers;
import com.mb.carlovers.adapter.OwnerAdapter;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container, false);
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Owner[] myOwners = null;
super.onCreate(savedInstanceState);
Bundle values = getActivity().getIntent().getExtras();
if(values != null)
{
myOwners = (Owner[]) values.getParcelableArray("test");
}
super.onActivityCreated(savedInstanceState);
ownerAdapter = new OwnerAdapter(getActivity(), R.layout.owner_detail , myOwners);
ownerAdapter.notifyDataSetChanged();
}
package com.mb.carlovers;
import java.util.List;
import com.mb.carlovers.asynctask.OnwerAsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class People extends FragmentActivity implements OnClickListener, OnItemSelectedListener {
private Button search;
private EditText etSearchBy, etSearchByID;
private Spinner spOption;
private String selectedOption = null;
private TextView tvErrorMessage;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.people);
InitializeVariables();
}
private void InitializeVariables()
{
etSearchBy = (EditText) this.findViewById(R.id.etByLastName);
etSearchByID = (EditText) this.findViewById(R.id.etCarID);
spOption = (Spinner) this.findViewById(R.id.spOption);
search = (Button) this.findViewById(R.id.bSearch);
search.setOnClickListener(this);
tvErrorMessage = (TextView) this.findViewById(R.id.tvErrorMessage);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.spOptions, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOption.setAdapter(adapter);
spOption.setOnItemSelectedListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
String searchByName = etSearchBy.getText().toString();
String searchById = etSearchByID.getText().toString();
if(selectedOption == null || selectedOption == "All")
{
if(searchByName.matches("") || searchById.matches(""))
{
tvErrorMessage.setText("You must select a last name and car id");
} else
{
}
} else if(selectedOption == "Name")
{
if(!searchByName.matches(""))
{
OnwerAsyncTask asynTask = new OnwerAsyncTask();
List<Owner> lt = null;
try {
lt = asynTask.execute("").get();
} catch (Exception e) {
e.printStackTrace();
}
Owner myOwners[] = lt.toArray(new Owner[lt.size()]);
Bundle data = new Bundle();
data.putParcelableArray("test", myOwners);
} else
{
tvErrorMessage.setText("You must enter the last name of the owner.");
}
} else if (selectedOption == "ID")
{
if(!searchById.matches(""))
{
String st = null;
String d = st;
} else
{
tvErrorMessage.setText("You must enter the car id that you'd like to search.");
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
switch(pos)
{
case 0:
selectedOption = "All";
break;
case 1:
selectedOption ="Name";
break;
case 2:
selectedOption ="ID";
break;
default:
selectedOption = null;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedOption ="ALL";
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Car;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CarAdapter extends ArrayAdapter<Car> {
private Context context;
private int layoutResourceId;
private Car data[] = null;
public CarAdapter(Context context, int resource, Car[] data) {
super(context, resource, data);
this.context = context;
this.layoutResourceId = resource;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CarHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CarHolder();
holder.tvMake = (TextView) row.findViewById(R.id.tvMake);
holder.tvModel = (TextView) row.findViewById(R.id.tvModel);
holder.tvYear = (TextView) row.findViewById(R.id.tvYear);
row.setTag(holder);
} else
{
holder = (CarHolder) row.getTag();
}
Car item = data[position];
holder.tvMake.setText(item.getMake().toString());
holder.tvModel.setText(item.getModel().toString());
holder.tvYear.setText(item.getYear().toString());
return row;
}
public static class CarHolder
{
TextView tvMake;
TextView tvModel;
TextView tvYear;
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Owner;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class OwnerAdapter extends ArrayAdapter<Owner> {
private Context context;
private int layoutResourceId;
private Owner data[] = null;
public OwnerAdapter(Context context, int textViewResourceId,Owner[] data) {
super(context, textViewResourceId, data);
this.context = context;
this.layoutResourceId = textViewResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OwnerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OwnerHolder();
holder.tvFName = (TextView) row.findViewById(R.id.tvFirstName);
holder.tvLName = (TextView) row.findViewById(R.id.tvLastName);
holder.tvCId = (TextView) row.findViewById(R.id.tvCarID);
row.setTag(holder);
} else
{
holder = (OwnerHolder) row.getTag();
}
Owner item = data[position];
holder.tvFName.setText(item.getFirstName());
holder.tvLName.setText("Example");
holder.tvCId.setText("1");
return row;
}
static class OwnerHolder
{
TextView tvFName;
TextView tvLName;
TextView tvCId;
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Car;
import android.os.AsyncTask;
public class CarAsyncTask extends AsyncTask<String, Void, List<Car>> {
private List<Car> item = null;
#Override
protected List<Car> doInBackground(String... params) {
item = new ArrayList<Car>();
item.add(new Car("Chevy","Caprice","2002"));
item.add(new Car("Chevy","Malibu","2014"));
item.add(new Car("Dodge","Stratus","2002"));
item.add(new Car("Saturn","L300","2004"));
return item;
}
#Override
protected void onPostExecute(List<Car> result) {
super.onPostExecute(result);
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Owner;
import android.os.AsyncTask;
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
#Override
protected List<Owner> doInBackground(String... params) {
try
{
items = new ArrayList<Owner>();
Owner own = new Owner();
own.setFirstName("John");
own.setLastName("Smith");
own.setCarId("1");
items.add(own);
Owner own1 = new Owner();
own1.setFirstName("Samantha");
own1.setLastName("Right");
own1.setCarId("2");
items.add(own1);
Owner own2 = new Owner();
own2.setFirstName("Regie");
own2.setLastName("Miller");
own2.setCarId("3");
items.add(own2);
Owner own3 = new Owner();
own3.setFirstName("Mark");
own3.setLastName("Adam");
own3.setCarId("4");
items.add(own3);
} catch(Exception ex)
{
ex.toString();
}
return items;
}
#Override
protected void onPostExecute(List<Owner> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
// car_detail.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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Car Detail Page" />
</LinearLayout>
// car_row.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" >
<TextView
android:id="#+id/tvMake"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvModel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
//customize_layout.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" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No record to be displayed."
/>
</LinearLayout>
//Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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=".Login" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etUserName"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
>
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etPassword"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:inputType="textPassword" />
<Button
android:id="#+id/bLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:text="Login" />
</LinearLayout>
//owner_detail.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" >
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvCarID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
// People.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="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by last name"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
/>
<EditText
android:id="#+id/etByLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by car id"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<EditText
android:id="#+id/etCarID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<Spinner
android:id="#+id/spOption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/spOptions"
/>
<TextView
android:id="#+id/tvErrorMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF0000"
android:layout_marginTop="10dp"
android:text="" />
<Button
android:id="#+id/bSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="2"
>
<fragment
android:id="#+id/fOwnerDetail"
android:name="com.mb.carlovers.OwnerDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<fragment
android:id="#+id/fragment1"
android:name="com.mb.carlovers.CarDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
/>
</LinearLayout>
</LinearLayout>
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(ownerAdapter);
}
}
Your code has a lot of problems:
1 Never call lifecycle methods on your own like you do in the OwnerDetail class with super.onActivityCreated(savedInstanceState);
2 Bundle values = getActivity().getIntent().getExtras(); ... values.getParcelableArray("test"); will normally fail because this piece of code will get the activity reference, get the Intent that started the activity and then try to find data passed in under the test key in that Intent. You don't pass such data to the People activity so there will be nothing to be found. You'd normally want to pass a Bundle containing the data at the moment of the creation of the fragment.
3 If you use the fragment in the xml layout you'll not be able to use a Bundle to pass data, instead you either add the fragment manually with transactions and then use a Bundle or you create a setter method in the fragment class and use that. So instead of Bundle data = new Bundle(); data.putParcelableArray("test", myOwners);, which does nothing, get a reference to your fragment and pass the myOwners array through a method.
4 Your AsyncTask will be pretty useless if you use them with .get() because the get() method will wait the AsyncTask to finish, blocking the UI tread as well. Instead you should just start the AsyncTask and then in the onPostExecute() pass the data around.
Here is an example with a simple method which will not change most of your code(which will happen if you manually add the fragments):
// where you start the owner asynctask
if(!searchByName.matches("")) {
OnwerAsyncTask asynTask = new OnwerAsyncTask(People.this);
asynTask.execute("");
}
//...
Then change the OnwerAsyncTask like this:
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
private FragmentActivity mActivity;
public OnwerAsyncTask(FragmentActivity activity) {
mActivity = activity;
}
// doInBackground()...
#Override
protected void onPostExecute(List<Owner> result) {
//I'm assuming that items is the data you want to return, so
// find the OwnerDetail fragment and directly assign the data
OwnerDetail fragment = (OwnerDetail)mActivity.getSupportFragmentManager().findFragmentById(R.id.fOwnerDetail);
fragment.setData(); // to setData you'll pass the data you have in the AsyncTask
// the items list? or you transform that into an array?
}
and in the OwnerDetail fragment:
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
public void setData() {
// update the adapter, create a new one etc.
}

How to add a checkbox in my gridview?

how do i add checkbox in my code? so user select multiple pictures using checkbox in gridview what do i do? I just want to add a checkbox in my gridview what do i do?
GridView gridView;
TextView textView;
File currentParent;
File[] currentFiles;
SimpleAdapter simpleAdapter;
File root1;
File root;
root1 = new File("/data/data/com.myexample.lock/files/");
currentParent = root1;
currentFiles = root1.listFiles();
currentFilePath = new String[currentFiles.length];
int count = 0;
for (File f : currentFiles) {
currentFilePath[count] = f.getAbsolutePath();
count++;
}
gridView = (GridView) findViewById(R.id.grid);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
if (currentFiles[position].isDirectory()) {
root = new File("/data/data/com.myexample.lock/files/" +
FileName(currentFilePath[position]) + "/");
currentFiles = root.listFiles();
inflateListView(currentFiles);
} else if (currentFiles[position].isFile()) {
openFile(currentFiles[position]);
}
}
});
private void inflateListView(File[] files) {
List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
for (int i = 0; i < files.length; i++) {
Map<String, Object> listItem = new HashMap<String, Object>();
if (files[i].isDirectory()) {
listItem.put("icon", R.drawable.folder);
listItem.put("fileName", files[i].getName()+
"("+files[i].list().length+")");
} else {
listItem.put("icon", files[i]);
}
listItems.add(listItem);
}
simpleAdapter = new SimpleAdapter(this,
listItems, R.layout.line,new String[] {
"icon", "fileName" }, new int[] { R.id.icon, R.id.file_name });
}
line.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="fill_parent"
android:background="#ffffff"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/file_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/icon"
android:paddingLeft="5dp"
android:textColor="#000000"
android:textSize="12dp" />
</RelativeLayout>
Use custom adapter for your gridView. In the getView method you can inflate any layout you want for the cell
This the example of how i made a custom listview with Imageview and TextView. I did this because i also wanted to delete multiple items selected in the listview.
This is my java code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DeleteData extends Activity {
Cursor cursor;
ListView lv_delete_data;
static ArrayList<Integer> listOfItemsToDelete;
SQLiteDatabase database;
private Category[] categories;
ArrayList<Category> categoryList;
private ArrayAdapter<Category> listAdapter;
ImageView iv_delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_data);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
manage_reload_list();
listOfItemsToDelete = new ArrayList<Integer>();
iv_delete = (ImageView) findViewById(R.id.imageViewDeleteDataDelete);
iv_delete.setClickable(true);
iv_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
}
else {
showDialog(
"Warning",
"Are you sure you want to delete these categories ? This will erase all records attached with it.");
}
}
});
lv_delete_data = (ListView) findViewById(R.id.listViewDeleteData);
lv_delete_data.setAdapter(listAdapter);
lv_delete_data.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) arg1
.findViewById(R.id.imageViewSingleRowDeleteData);
Category category = (Category) imageView.getTag();
if (category.getChecked() == false) {
imageView.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageView.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
}
private void showDialog(final String title, String message) {
AlertDialog.Builder adb = new Builder(DeleteData.this);
adb.setTitle(title);
adb.setMessage(message);
adb.setIcon(R.drawable.ic_launcher);
String btn = "Ok";
if (title.equals("Warning")) {
btn = "Yes";
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
adb.setPositiveButton(btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
if (title.equals("Warning")) {
for (int i : listOfItemsToDelete) {
// -------first delete from category table-----
// database.delete("category", "cat_id=?",
// new String[] { i + "" });
// ---------delete from category_fields
database.delete("category_fields", "cat_id=?",
new String[] { i + "" });
// --------now fetch rec_id where cat_id =
// i-----------------
cursor = database.query("records_data",
new String[] { "rec_id" }, "cat_id=?",
new String[] { i + "" }, null, null, null);
if (cursor.getCount() == 0)
cursor.close();
else {
ArrayList<Integer> al_tmp_rec_id = new ArrayList<Integer>();
while (cursor.moveToNext())
al_tmp_rec_id.add(cursor.getInt(0));
cursor.close();
for (int i1 : al_tmp_rec_id) {
database.delete("records_fields_data",
"rec_id=?", new String[] { i1 + "" });
database.delete("record_tag_relation",
"rec_id=?", new String[] { i1 + "" });
}
// ---------delete from records_data-------
database.delete("records_data", "cat_id=?",
new String[] { i + "" });
cursor.close();
}
}
showDialog("Success",
"Categories, with their records, deleted successfully.");
} else {
database.close();
listOfItemsToDelete.clear();
manage_reload_list();
lv_delete_data.setAdapter(listAdapter);
}
}
});
AlertDialog ad = adb.create();
ad.show();
}
protected void manage_reload_list() {
loadDatabase();
categoryList = new ArrayList<Category>();
// ------first fetch all categories name list-------
cursor = database.query("category", new String[] { "cat_id",
"cat_description" }, null, null, null, null, null);
if (cursor.getCount() == 0) {
Toast.makeText(getBaseContext(), "No categories found.",
Toast.LENGTH_SHORT).show();
cursor.close();
} else {
while (cursor.moveToNext()) {
categories = new Category[] { new Category(cursor.getInt(0),
cursor.getString(1)) };
categoryList.addAll(Arrays.asList(categories));
}
cursor.close();
}
listAdapter = new CategoryArrayAdapter(this, categoryList);
}
static class Category {
String cat_name = "";
int cat_id = 0;
Boolean checked = false;
Category(int cat_id, String name) {
this.cat_name = name;
this.cat_id = cat_id;
}
public int getId() {
return cat_id;
}
public String getCatName() {
return cat_name;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
public void toggleChecked() {
checked = !checked;
}
}
static class CategoryViewHolder {
ImageView imageViewCheck;
TextView textViewCategoryName;
public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
imageViewCheck = iv_check;
textViewCategoryName = tv_category_name;
}
public ImageView getImageViewCheck() {
return imageViewCheck;
}
public TextView getTextViewCategoryName() {
return textViewCategoryName;
}
}
static class CategoryArrayAdapter extends ArrayAdapter<Category> {
LayoutInflater inflater;
public CategoryArrayAdapter(Context context, List<Category> categoryList) {
super(context, R.layout.single_row_delete_data,
R.id.textViewSingleRowDeleteData, categoryList);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Category category = (Category) this.getItem(position);
final ImageView imageViewCheck;
final TextView textViewCN;
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_delete_data,
null);
imageViewCheck = (ImageView) convertView
.findViewById(R.id.imageViewSingleRowDeleteData);
textViewCN = (TextView) convertView
.findViewById(R.id.textViewSingleRowDeleteData);
convertView.setTag(new CategoryViewHolder(imageViewCheck,
textViewCN));
}
else {
CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
.getTag();
imageViewCheck = viewHolder.getImageViewCheck();
textViewCN = viewHolder.getTextViewCategoryName();
}
imageViewCheck.setFocusable(false);
imageViewCheck.setFocusableInTouchMode(false);
imageViewCheck.setClickable(true);
imageViewCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView iv = (ImageView) v;
Category category = (Category) iv.getTag();
if (category.getChecked() == false) {
imageViewCheck.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageViewCheck
.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
imageViewCheck.setTag(category);
if (category.getChecked() == true)
imageViewCheck.setImageResource(R.drawable.set_check);
else
imageViewCheck.setImageResource(R.drawable.set_basecircle);
textViewCN.setText(category.getCatName());
return convertView;
}
}
private void loadDatabase() {
database = openOrCreateDatabase("WalletAppDatabase.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
This is my main layout code:
<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:background="#ffffff"
tools:context=".DeleteData" >
<RelativeLayout
android:id="#+id/relativeLayoutDeleteDataTopBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<TextView
android:id="#+id/textViewDeleteDataScreenTitle"
style="#style/screen_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Data" />
<ImageView
android:id="#+id/imageViewDeleteDataDelete"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/set_delete" />
</RelativeLayout>
<View
android:id="#+id/viewDeleteData"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="#+id/relativeLayoutDeleteDataTopBar"
android:background="#drawable/shadow" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/linearLayoutDeleteDataAdMobBanner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" >
<com.google.ads.AdView
android:id="#+id/adViewDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="a1512f50d8c3692"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" />
</LinearLayout>
<ListView
android:id="#+id/listViewDeleteData"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#BDBDBD"
android:dividerHeight="1dp"
android:layout_below="#+id/viewDeleteData"
android:layout_above="#+id/linearLayoutDeleteDataAdMobBanner" >
</ListView>
</RelativeLayout>
And this is my custom layout code which i use to inflate in listview:
<?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="wrap_content"
android:background="#ffffff"
android:padding="15dp" >
<TextView
android:id="#+id/textViewSingleRowDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
style="#style/listview_only_textview"
android:text="Category" />
<ImageView
android:id="#+id/imageViewSingleRowDeleteData"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/set_basecircle" />
</RelativeLayout>

Categories

Resources