I am storing values in arraylist as{india,pakisthan,srilanka,nepal,malasiya,australia,ireland} when I set this list to BaseAdapter the last element is not showing last item in listview when listview extends device screen. It showing only India, Pakisthan, Srilanka, Nepal, Malasiaya and Australia was breaking and Ireland was not showing. My ListFragment class is
package com.example.mynavigationtab;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class AndroidFragment extends ListFragment
{
ArrayList<CountryObject> mCountry = new ArrayList<CountryObject>();
ArrayList<String> mCoun = new ArrayList<String>();
CountryObject country = new CountryObject();
AndroidAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
LoadUrl();
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
public void LoadUrl()
{
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("naren", "naren"));
new GetJsonData().execute(getString(R.string.tag_url),pairs,ThreadCode.THREAD_URL, handler);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
getActivity().removeDialog(0);
switch (msg.what) {
case ThreadCode.THREAD_URL:
final String result = (String) msg.obj;
LoadJson(result);
break;
default:
break;
}
}
};
public void LoadJson(String result)
{
try
{
JSONObject mJson1 = new JSONObject(result);
JSONArray mResult = mJson1.getJSONArray("result");
mCountry = new ArrayList<CountryObject>();
for(int i=0; i<mResult.length(); i++)
{
JSONObject mRes = mResult.getJSONObject(i);
JSONArray mCount = mRes.getJSONArray("Country");
JSONObject mCoun = mCount.getJSONObject(i);
CountryObject mSetData = new CountryObject();
mSetData.setmCountry(mCoun.getString("name"));
mCountry.add(mSetData);
CountryObject mSetData1 = new CountryObject();
mSetData1.setmCountry(mCoun.getString("name1"));
mCountry.add(mSetData1);
CountryObject mSetData2 = new CountryObject();
mSetData2.setmCountry(mCoun.getString("name2"));
mCountry.add(mSetData2);
CountryObject mSetData3 = new CountryObject();
mSetData3.setmCountry(mCoun.getString("name3"));
mCountry.add(mSetData3);
CountryObject mSetData4 = new CountryObject();
mSetData4.setmCountry(mCoun.getString("name4"));
mCountry.add(mSetData4);
CountryObject mSetData5 = new CountryObject();
mSetData5.setmCountry(mCoun.getString("name5"));
mCountry.add(mSetData5);
CountryObject mSetData6 = new CountryObject();
mSetData6.setmCountry(mCoun.getString("name6"));
mCountry.add(mSetData6);
CountryObject mSetData7 = new CountryObject();
mSetData7.setmCountry(mCoun.getString("name7"));
mCountry.add(mSetData7);
CountryObject mSetData8 = new CountryObject();
mSetData8.setmCountry(mCoun.getString("name8"));
mCountry.add(mSetData8);
}
}
catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
String mMessage = "Error parsing JSON data from server. Please try again.";
showToast(mMessage);
}
}
public void showToast(String message) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getActivity(), message, duration);
toast.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
LoadUrl();
}
}`
//Adapter class
package com.example.mynavigationtab;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class AndroidAdapter extends BaseAdapter
{
ArrayList<String> mCountry = new ArrayList<String>();
Context mContext;
TextView mCountryName;
public AndroidAdapter(Context androidFragment,ArrayList<String> mCoun)
{
mCountry = mCoun;
mContext = androidFragment;
}
#Override
public int getCount()
{
return mCountry.size();
}
#Override
public Object getItem(int position)
{
return mCountry.get(position);
}
#Override
public long getItemId(int position)
{
return mCountry.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
converview = null;
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.adapter_list, parent,false);
mCountryName = (TextView) convertView.findViewById(R.id.textOne);
mCountryName.setText(mCountry.get(position));
}
return convertView;
}
}
// Xml Layout for adapter_list.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textOne"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:padding="2dp"
android:textStyle="bold"/>
</RelativeLayout>
//Json File
{
result: [
{
Country: [
{
name: "India",
name1: "Pakisthan",
name2: "Bangaldesh",
name3: "Australia",
name4: "Ireland",
name5: "SriLanka",
name6: "Nepal",
name7: "USA",
name8: "Russia"
}
],
States: [
{
states: "Tamil Nadu",
states1: "Andhra",
states2: "Karnataka",
states3: "Kerala"
}
],
District: [
{
district: "Krishnagiri",
district1: "Dharmapuri",
district2: "Salem",
district3: "Hosur"
}
]
}
]
}
May this solve your problem :
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.adapter_list, parent,false);
mCountryName = (TextView) convertView.findViewById(R.id.textOne);
}
mCountryName.setText(mCountry.get(position));//Write this after condition
One problem is that you're setting the text only when convertView is null. You should make sure that the line mCountryName.setText(mCountry.get(position)); is executed every single time, otherwise some items will not show up.
Atlast I solved it.............
The Problem is in my xml layout. That i have mentioned a weight for framelayout in TabHost
//Modified xml layout
<?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DBE9F4">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/frame_shape"
android:layout_weight="0" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#android:color/white">
</FrameLayout>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
</TabHost>
Related
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 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.
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!
I am trying to display a custom listview but nothing appears.
My activity:
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.example.elnoorgeh.ServerAPI;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class BlogFragment extends Fragment {
JSONArray jArray;
TextView title;
RelativeLayout layout;
int previousID = 0;
int currentID = 0;
ArrayList<String> titles;
ArrayList<String> contents;
ListView list;
public BlogFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blog, container,
false);
new AsyncFetch().execute();
return rootView;
}
private class AsyncFetch extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
jArray = new JSONArray();
jArray = ServerAPI.getData();
titles = new ArrayList<String>();
contents = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
String blogTitle = null;
String content = null;
try {
blogTitle = jArray.getJSONObject(i).getString("title");
content = jArray.getJSONObject(i).getString("content");
titles.add(blogTitle);
contents.add(content);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(blogTitle);
System.out.println(content);
}
// display(titles, contents);
return null;
}
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeAllViews();
CustomList adapter = new CustomList(getActivity(), titles);
list = new ListView(getActivity());
System.out.println("list done");
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
}
public void display(ArrayList<String> t, ArrayList<String> c) {
}
}
Custom ListView class:
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> web;
// private final Integer[] imageId;
public CustomList(Activity context, ArrayList<String>web) {
super(context, R.layout.fragment_listview);
this.context = context;
this.web = web;
// this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.fragment_listview, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText((CharSequence) web.get(position));
// imageView.setImageResource(imageId[position]);
return rowView;
}
}
fragment_blog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/blogPage"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="20"
android:singleLine="false"
android:textSize="16dp" />
</RelativeLayout>
fragment_listview:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="50dp" />
</TableRow>
</TableLayout>
I can't find any errors or notice something irregular, so why is that happening?
you should extend BaseAdapter and implement abstract methods
#Override
public int getCount() {
return web.size();
}
#Override
public Object getItem(int position) {
return web.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
also you might change
txtTitle.setText((CharSequence) web.get(position));
to
txtTitle.setText((CharSequence) getItem(position));
now your adapter don't know size of web array
edit:
you can get one inflater in constructor and keep in class, no need to getting inflater each time (little bit better for perfomance)
LayoutInflater inflater = context.getLayoutInflater();
edit 2:
localhost put proper comment - you are removing all Views from RelativeLayout, also ListView, and creating new ListView without adding to Relative. keeping reference will not auto-add View
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeView(getView().findViewById(R.id.txtLabel);
//assuming you need to remove only txtLabel
CustomList adapter = new CustomList(getActivity(), titles);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
I haven't touched this codebase in a couple of months. Now that I've picked it up again, some code that I didn't think I'd changed has stopped working: All listfragment listviews in the app populated by a simplecursoradapter have stopped working and are just blank. At first I thought the cursor or the database was at fault or that perhaps the adapter wasn't being set correctly, so I added some debugging to the onLoadFinished:
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
Log.d("IndexListFragment", "Rows returned: " + cursor.getCount());
Log.d("IndexListFragment", cursor.getColumnName(0));
Log.d("IndexListFragment", mAdapter.toString());
Log.d("IndexListFragment", this.getListView().getAdapter().toString());
mAdapter.swapCursor(cursor);
}
This returns what I'd expect:
IndexListFragment: Rows returned: 2324
IndexListFragment: _id
IndexListFragment: android.support.v4.widget.SimpleCursorAdapter#41d06a18
IndexListFragment: android.support.v4.widget.SimpleCursorAdapter#41d06a18
So as far as I can tell, the cursor is there and full of data, but swapping it in doesn't get the listview populated. Any ideas?
For completeness, here's the onCreate where the adapter is created and set:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = new String[] { GuidebookProvider.COL_NAME,
GuidebookProvider.COL_GRADE };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null, from, to, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
And the onCreateLoader:
#Override
public Loader<Cursor> onCreateLoader(int loaderId, Bundle loaderArgs) {
String orderBy = GuidebookProvider.COL_NAME;
String[] projection = new String[] { GuidebookProvider.COL_ID, GuidebookProvider.COL_NAME, GuidebookProvider.COL_GRADE };
return new CursorLoader(getActivity(),
GuidebookProvider.CONTENT_URI_CLIMB, projection, null, null,
orderBy);
}
Edit: I've done a little more work debugging this issue. The fragment works fine if I run it directly from an activity like this:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;
public class TestActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
frame.setId(android.R.id.content);
if (savedInstanceState == null) {
Bundle args = new Bundle();
args.putInt(IndexListFragment.ARGUMENT_INDEX_TYPE, IndexListFragment.IndexType.ALPHA.value);
Fragment indexListFragment = new IndexListFragment();
indexListFragment.setArguments(args);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(android.R.id.content, indexListFragment).commit();
}
}
}
However, calling it as part of a Tab ends up with a blank tab:
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
public class TestActivity extends FragmentActivity {
private FragmentTabHost mTabHost;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tab_host);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
Bundle args = new Bundle();
args.putInt(IndexListFragment.ARGUMENT_INDEX_TYPE,
IndexListFragment.IndexType.ALPHA.value);
Drawable drawable = null;
mTabHost.addTab(mTabHost.newTabSpec("A-Z")
.setIndicator("A-Z", drawable), IndexListFragment.class, args);
}
}
Here's my xml for the tabhost:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
The fact that the fragment populates correctly when called directly but not when called from within a tab seems to show that the problem isn't at all with the cursors or adapters but with the way the listfragment operating inside a tab.
Can anyone point out what I've done wrong (or what's changed in the last couple of updates of the SDK) to break this code? It used to work fine.
This Code may help you just try it
ViewAllLesson.java :
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import com.xyz.R;
import com.xyz.db.LessonDatabaseConnector;
import com.xyz.pojo.AssignmentPojo;
import com.xyz.pojo.LessonPojo;
public class ViewAllLessons extends Fragment {
public LessonDatabaseConnector dao;
private View rootView;
List<LessonPojo> lessons;
ArrayList<String> con = new ArrayList<String>();
LayoutInflater mInflater;
LessonCustomAdapter lessonCustomAdapter;
private ListView listView;
public static CheckBox selectAll;
private Button deleteBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.add_exams);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.lesson_view_all_list, container,
false);
// dao = new AssignmentDatabaseConnector(getActivity());
listView = (ListView) rootView.findViewById(R.id.Lesson_ListAll);
selectAll = (CheckBox) rootView.findViewById(R.id.SelectAll);
deleteBtn = (Button) rootView.findViewById(R.id.LessonDeleteBtn);
Button addNew = (Button) rootView.findViewById(R.id.LessonAddNewBtn);
addNew.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity(), "hi",
// Toast.LENGTH_LONG).show();
Lesson lesson = new Lesson();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, lesson).commit();
}
});
// viewgr.setScrollContainer(false);
dao = new LessonDatabaseConnector(getActivity());
lessons = dao.getAllLessonList();
lessonCustomAdapter = new LessonCustomAdapter(getActivity(), lessons,
this);
listView.setAdapter(lessonCustomAdapter);
/* To Check List View is empty */
if (lessons.size() <= 0) {
View empty = rootView.findViewById(R.id.empty);
ListView list = (ListView) rootView
.findViewById(R.id.Lesson_ListAll);
list.setEmptyView(empty);
listView.setVisibility(0);
empty.setVisibility(1);
}
selectAll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity(), "hi",
// Toast.LENGTH_LONG).show();
if (((CheckBox) v).isChecked()) {
LessonCustomAdapter.flag = true;
lessonCustomAdapter.notifyDataSetChanged();
} else {
LessonCustomAdapter.flag = false;
LessonCustomAdapter.checkedvalue.clear();
lessonCustomAdapter.notifyDataSetChanged();
}
}
});
// Set the list adapter and get TODOs list via DAO
deleteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LessonDatabaseConnector dao = new LessonDatabaseConnector(
getActivity());
for (int i = 0; i < LessonCustomAdapter.checkedvalue.size(); i++) {
//
System.out
.println("===========LessonCustomAdapter.checkedvalue.size()==========SIZE======>>>>"
+ LessonCustomAdapter.checkedvalue.size());
System.out
.println("===========DELETED LESSON=================>>>>"
+ LessonCustomAdapter.checkedvalue.get(i));
dao.DeleteLesson(LessonCustomAdapter.checkedvalue.get(i));
}
LessonCustomAdapter.flag = false;
ViewAllLessons viewAllLessons = new ViewAllLessons();
getFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, viewAllLessons)
.commit();
// finish();
}
});
return rootView;
}
private List<AssignmentPojo> getAllAssignmentsList() {
// TODO Auto-generated method stub
return null;
}
}
LessonCustomAdapter :
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.xyz.R;
import com.xyz.pojo.LessonPojo;
public class LessonCustomAdapter extends BaseAdapter {
protected static boolean flag = false;
private TextView mLessonTitle, mLessonDate;
private final Context context;
List<LessonPojo> Lessons;
private ViewAllLessons viewAllLessons;
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
private CheckBox SingleChk;
public static ArrayList<Long> checkedvalue = new ArrayList<Long>();
LessonCustomAdapter(Context context, List<LessonPojo> Lessons2,
ViewAllLessons viewAllLessons) {
this.context = context;
this.Lessons = Lessons2;
this.viewAllLessons = viewAllLessons;
for (int i = 0; i < Lessons2.size(); i++) {
itemChecked.add(i, false); // initializes all items value with false
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Lessons.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
rowView = inflater.inflate(R.layout.lesson_view_row_list, parent,
false);
}
mLessonDate = (TextView) rowView.findViewById(R.id.LessonDate);
mLessonDate.setText(Lessons.get(position).getLdate());
mLessonTitle = (TextView) rowView.findViewById(R.id.LessonTitle);
mLessonTitle.setText(Lessons.get(position).getLtitle());
SingleChk = (CheckBox) rowView.findViewById(R.id.singleChk);
/*
* if (flag) { System.out.println("66666666666666666666666666666666" +
* flag); for (int i = 0; i < Lessons.size(); i++) {
* SingleChk.setChecked(flag); SingleChk.setEnabled(!flag); }
*
* } else { SingleChk.setChecked(itemChecked.get(position)); }
*/
checkedvalue.clear();
if (ViewAllLessons.selectAll.isChecked()) {
SingleChk.setChecked(true);
Boolean val = false;
for (int i = 0; i < Lessons.size(); i++) {
checkedvalue.add(Long.parseLong(Lessons.get(i).getId()));
System.out
.println("ADD SUCCEFULLYYYYYYYY ====================== "
+ Long.parseLong(Lessons.get(position).getId()));
}
} else {
SingleChk.setChecked(false);
checkedvalue.clear();
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
ViewSingleLesson viewSingleLesson = new ViewSingleLesson();
bundle.putString("ID", Lessons.get(position).getId());
bundle.putString("TITLE", Lessons.get(position).getLtitle());
bundle.putString("COURSE", Lessons.get(position).getLcourse());
bundle.putString("LEVEL", Lessons.get(position).getLlevel());
bundle.putString("CLASS", Lessons.get(position).getLclass());
bundle.putString("DATE", Lessons.get(position).getLdate());
bundle.putString("DESC", Lessons.get(position).getLdesc());
bundle.putString("ATTACH", Lessons.get(position).getLfilepath());
viewSingleLesson.setArguments(bundle);
viewAllLessons.getFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, viewSingleLesson)
.commit();
}
});
SingleChk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Boolean val = false;
Toast.makeText(context, "hi " + Lessons.get(position).getId(),
Toast.LENGTH_LONG).show();
if (((CheckBox) v).isChecked()) {
for (int i = 0; i < checkedvalue.size(); i++) {
if (checkedvalue.get(i) == Long.parseLong(Lessons.get(
position).getId())) {
val = true;
System.out
.println("DUPLICATE ====================== "
+ Long.parseLong(Lessons.get(
position).getId()));
} else {
val = false;
}
}
if (val == false) {
checkedvalue.add(Long.parseLong(Lessons.get(position)
.getId()));
System.out
.println("ADD SUCCEFULLYYYYYYYY ====================== "
+ Long.parseLong(Lessons.get(position)
.getId()));
}
} else {
ViewAllLessons.selectAll.setChecked(false);
checkedvalue.remove(Long.parseLong(Lessons.get(position)
.getId()));
System.out
.println("Removed SUCCEFULLYYYYYYYY ====================== "
+ Integer.parseInt(Lessons.get(position)
.getId()));
// itemChecked.set(position, false);
}
}
});
return rowView;
}
}
Got a chance to have a look at this today and finally sorted it out. The problem was in my xml layout setup. Oddly, according to my git repository, this file hasn't changed for 9 months so I guess I was doing something that only worked by accident. I found a tutorial FragmentTabHosts with a different layout and updated my layout to:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
</LinearLayout>
That somehow fixed the issue. A bit more hunting around revealed an example layout xml for FragmentTabHost in the TabActivity documentation: http://developer.android.com/reference/android/app/TabActivity.html
I updated to use the version found in the documentation and it also works:
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
Given I found it in Android's documentation, I'll stick with this version.