Hi onListItemClick for listview is not working. Here i am fetching datas from SQLite using AsyncTask and displaying it in a list view. And i wants to do some actions when a list in a listview has clicked. But the click is not happening. I had tried a lot for this. Please help me.
Here is my code
package com.applexus.app.mobilesalesorder;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import com.applexus.app.library.sql.SqlConnector;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class SoldToPartiesList extends ListActivity {
private ArrayList<String> data = new ArrayList<String>();
private ArrayList<String> idk = new ArrayList<String>();
private ArrayList<String> name1 = new ArrayList<String>();
private ArrayList<String> inco1 = new ArrayList<String>();
private ArrayList<String> email = new ArrayList<String>();
private ArrayList<String> tel = new ArrayList<String>();
private ArrayList<String> vwerk = new ArrayList<String>();
private SharedPreferences prefs;
private String prefNamesalesorgid = "salesorgid";
private String prefNamedistchnlid = "distchnlid";
private String prefNamedivid = "divid";
private String prefName = "mso";
private TextView titlename;
private static class ViewHolder {
TextView tvlist;
TextView tvlistsmall;
}
private class EfficientAdapter extends BaseAdapter {
private Context context;
LayoutInflater inflater;
public EfficientAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
final int place = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listso, null);
holder = new ViewHolder();
holder.tvlist = (TextView) convertView
.findViewById(R.id.textViewlist);
holder.tvlistsmall = (TextView) convertView
.findViewById(R.id.textView1);
convertView.setTag(holder);
//
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvlist.setText(idk.get(position));
holder.tvlistsmall.setText(data.get(position));
return convertView;
}
}
Map<String, String> map = new TreeMap<String, String>();
SqlConnector con;
String salorg;
String distch;
String division;
Context co = this;
Boolean searchable=false;
TextView tvmc;
TextView tvmn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.materiallist);
titlename = (TextView) findViewById(R.id.textViewtitle);
titlename.setText(R.string.soldtoparties);
tvmc=(TextView)findViewById(R.id.textViewmc);
tvmn=(TextView)findViewById(R.id.textViewmn);
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
salorg = (prefs.getString(prefNamesalesorgid, ""));
distch = (prefs.getString(prefNamedistchnlid, ""));
division=(prefs.getString(prefNamedivid, ""));
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { null });
// ListView lv=(ListView)findViewById(android.R.id.list);
// lv.setOnItemSelectedListener(new )
}
EditText es;
LinearLayout ls;
LinearLayout mc;
LinearLayout mn;
Boolean searchFlag = false;
String search;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
es = (EditText) findViewById(R.id.editTextSearch);
ls = (LinearLayout) findViewById(R.id.linearLayoutsearch);
}
private class DownloadWebPageTasksearch extends
AsyncTask<String, Void, String> {
Cursor c;
ProgressBar pb;
#Override
protected String doInBackground(String... urls) {
con = new SqlConnector(co);
try {
if (searchFlag) {
c = con.select("select Kunnr,Name,Name1,Inco1,Vwerk,SmtpAddr,Telf1 from tb_soldtoparties where salesorg='"
+ salorg + "' and channel='" + distch + "' and Name like '%"+search+"%' and division='"+division+"';");
} else {
c = con.select("select Kunnr,Name,Name1,Inco1,Vwerk,SmtpAddr,Telf1 from tb_soldtoparties where salesorg='"
+ salorg + "' and channel='" + distch + "' and Kunnr like '%"+search+"%' and division='"+division+"';");
}
} catch (Exception e) {
e.printStackTrace();
}
int in = c.getCount();
c.moveToFirst();
for (int i = 0; i < in; i++) {
idk.add(c.getString(0));
data.add(c.getString(1));
name1.add(c.getString(2));
inco1.add(c.getString(3));
vwerk.add(c.getString(4));
email.add(c.getString(5));
tel.add(c.getString(6));
c.moveToNext();
}
return null;
}
#Override
protected void onPostExecute(String result) {
setListAdapter(new EfficientAdapter(SoldToPartiesList.this));
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
searchable=true;
con.close();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
idk.clear();
data.clear();
name1.clear();
inco1.clear();
vwerk.clear();
email.clear();
tel.clear();
setListAdapter(new EfficientAdapter(SoldToPartiesList.this));
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.VISIBLE);
searchable=false;
}
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
Cursor c;
ProgressBar pb;
#Override
protected String doInBackground(String... urls) {
con = new SqlConnector(co);
try {
c = con.select("select Kunnr,Name,Name1,Inco1,Vwerk,SmtpAddr,Telf1 from tb_soldtoparties where salesorg='"
+ salorg + "' and channel='" + distch + "' and division='"+division+"';");
} catch (Exception e) {
e.printStackTrace();
}
int in = c.getCount();
c.moveToFirst();
Log.d("size", "" + in + "");
for (int i = 0; i < in; i++) {
idk.add(c.getString(0));
data.add(c.getString(1));
name1.add(c.getString(2));
inco1.add(c.getString(3));
vwerk.add(c.getString(4));
email.add(c.getString(5));
tel.add(c.getString(6));
c.moveToNext();
}
return null;
}
#Override
protected void onPostExecute(String result) {
setListAdapter(new EfficientAdapter(SoldToPartiesList.this));
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
searchable=true;
con.close();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
idk.clear();
data.clear();
name1.clear();
inco1.clear();
vwerk.clear();
email.clear();
tel.clear();
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.VISIBLE);
searchable=false;
}
}
// class ClickOnList implements OnItemClickListener
// {
// #Override
// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
// long arg3) {
// Log.d("ListView", "Position"+arg2);
//
// }
//
// }
// public OnItemClickListener theListListener = new OnItemClickListener() {
//
// public void onItemClick(android.widget.AdapterView<?> parent, View v, int position, long id) {
// Log.d("position",position+"");
// } };
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int place=position;
Log.d("position",position+"");
}
}
And Layout code is materiallist.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:background="#color/bluebg"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/bar1"
android:gravity="center_vertical"
android:minHeight="50dp"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:layout_weight="1"
android:gravity="center_vertical|left" >
<TextView
android:id="#+id/textViewtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:shadowColor="#000000"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="1.5"
android:text="#string/materials"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:gravity="center" >
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center" >
<EditText
android:id="#+id/editTextSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:hint="#string/search"
android:imeOptions="actionDone"
android:inputType="textUri" >
</EditText>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayoutsearch"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center" android:clickable="true">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="#drawable/search" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout6"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/listbg2" >
<LinearLayout
android:id="#+id/linearLayoutmc"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/lbg1"
android:gravity="center" >
<TextView
android:id="#+id/textViewmc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Code"
android:textColor="#color/black" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayoutmn"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/lbg2"
android:gravity="center" >
<TextView
android:id="#+id/textViewmn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Name"
android:textColor="#color/black" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout10"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/offwhite" >
</ListView>
</LinearLayout>
</LinearLayout>
And listso3.xml is
<?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="wrap_content"
android:background="#drawable/lbg"
android:orientation="vertical"
>
<TextView
android:id="#+id/textViewNamelist3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/black"
android:focusable="false"/>
<TextView
android:id="#+id/textViewKunn2list3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/black"
android:focusable="false"/>
</LinearLayout>
Add below code to your TextView in the XML
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
and try again.
Another simple solution: add android:descendantFocusability="blocksDescendants" to the root viewgroup.
You should add android:focusable="false" for ListView row items to make ListView Clikable. Because the views in the row of ListView gain the focus so ListView is not focusable. So, in your case you can add android:focusable="false" to the TextViews of your ListView row.
I had the same symptoms, and it drove me crazy for a while. Adding android:focusable="false" for the list items as suggested above fixed the problem for me.
But the real issue was that I had set android:textIsSelectable="true" for my list items (in response to a Warning generated by Eclipse); setting android:textIsSelectable="false" fixed the problem for me, and I did not need the android:focusable="false" option at all.
The workaround I found avoid the
AdapterView.OnItemClickListener mMessageClickedHandler=new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
};
on the ListView, but exploit the Adapter constructor that takes a Context as parameter:
myCustomAdapter=new MyCustomAdapter(ActivityName.this,...)
Passing ActivityName.this is possible to cast the Context in the adapter's class as ActivityName in a safe way and use its methods working like callbacks:
((ActivityName)context).activityMethod()
Given that the getView() method of the Adapter class has a position parameter, is possible to pass this value to the activityMethod(int position) in order to know which list item has been pressed into the Activity where the ListView is.
Another solution.
if you have many child-control,and its to trouble to add android:focusable="false" to every child-control,you can add android:descendantFocusability="blocksDescendants" to its parent-control.try it.
I struggled with this for a while - none of the provided solutions worked for me. In the end I found that having a call to getListView() in my onViewCreated() method did the trick, although I have no idea why. This is for a Fragment rather than an Activity; not sure if this makes any difference.
public class NewsListFragment extends ListFragment {
private ListView listView;
...
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
newsListView = getListView();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// this now works as expected
}
}
I was also struggling with this issue and none of the suggested solutions worked. My problem was that I did an override for onViewCreated but didn't call super.onViewCreated(view, savedInstanceState);. Hopefully this will help someone else so they don't spend hours trying to figure out what's going on.
I struggled as I by mistake put android:inputType="textCapWords" with the textbox after removing it it is fixed
Only the line below worked for me:
android:descendantFocusability="blocksDescendants"
The whole list_view_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--android:focusableInTouchMode="false"-->
<!--android:focusable="false"-->
<!--android:clickable="false"-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/checkBox_list_view_checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/checkBox_list_view_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The above is to be used in getView like:
convertView=LayoutInflater.from(getContext())
.inflate(R.layout.list_view_item, parent, false);
`
Related
I am try to show Custom List View using Custom Adapter. that is showing data nicely but when i try to add new Item form EditTxt on click of Button then getting error.
Could not execute method for android:onClick
i am not able to add new Item in this list. here name will come form EditText and other item will constant. i try many method but not getting my solution. Another issue is , Activity is opening little late. can you tell me issue behind this.. please check Code...
Activity_phone_book.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="280dp"
android:layout_height="40dp"
android:layout_gravity="left"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:gravity="center|center_horizontal|center_vertical"
android:text="Type Your Name"
android:textSize="14sp"
android:id="#+id/addNewName"/>
<Button
android:layout_width="100dp"
android:id="#+id/addNew"
android:onClick="addNewData"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:text="Add New" />
</LinearLayout>
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_array.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" >
<ImageView
android:id="#+id/userImage"
android:layout_width="109dp"
android:layout_height="90dp"
android:padding="5dp" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#4d4d4d"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
PhoneBook Activity
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class PhoneBook extends AppCompatActivity {
// Declare variable types
int[] images={R.drawable.pankaj,R.drawable.logo_red,R.drawable.about_us,R.drawable.buddy_1,
R.drawable.buddy_2,R.drawable.contact_us,R.drawable.head_659651_640,R.drawable.login1,
R.drawable.login2,R.drawable.login3};
String[] names={"Pankaj Kumar","Rahul","Prabhash","Rima","Kum","Rupali","Amrawati","Nabhya",
"Nidhi","Sonu"};
String[] profiles={ "Web Developer","Software Developer","Web Developer","Software Developer",
"Web Developer","Software Developer","Web Developer","Software Developer",
"Web Developer","Software Developer" };
Button addNew ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_book);
ListView listview = (ListView) findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter();
listview.setAdapter(customAdapter);
}
// here i want to add new Item using this function
public void addNewData( View v)
{
Toast.makeText(this, "length " + images.length, Toast.LENGTH_SHORT).show();
# here i am try to add new item in Array. but getting error. many method applied here but now worked.please tell me how can i add new item form Edit Text...
images = new int[R.drawable.login3];
}
class CustomAdapter extends BaseAdapter{
#Override
public int getCount() {
return images.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.activity_array ,null);
ImageView imageView = (ImageView)convertView.findViewById(R.id.userImage);
TextView textView = (TextView)convertView.findViewById(R.id.userName);
TextView textView1 = (TextView)convertView.findViewById(R.id.profile);
imageView.setImageResource(images[position]);
textView.setText(names[position]);
textView1.setText(profiles[position]);
return convertView;
}
}
class CustomAdapter1 extends BaseAdapter
{
#Override
public int getCount() {
return images.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.activity_array ,null);
ImageView imageView = (ImageView)convertView.findViewById(R.id.userImage);
TextView textView = (TextView)convertView.findViewById(R.id.userName);
TextView textView1 = (TextView)convertView.findViewById(R.id.profile);
imageView.setImageResource(images[position]);
textView.setText(names[position]);
textView1.setText(profiles[position]);
return convertView;
}
}
}
This is my homepage.xml - where list view is placed:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical"
tools:context="com.andapps.azaz.e_recommender.HomePage">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Category:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<Spinner
android:id="#+id/spcategorieshomepage"
android:layout_width="match_parent"
android:layout_height="35sp"
android:layout_marginRight="14sp"
android:spinnerMode="dropdown"
android:textColor="#color/textColor"
>
</Spinner>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/llhome"
android:gravity="center"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp">
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
</LinearLayout>
And also my customlist.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product ID:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
android:id="#+id/tvproductid"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Name:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
android:id="#+id/tvproductname"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Rating:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<RatingBar
android:id="#+id/ratingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:max="5"
android:numStars="5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
android:id="#+id/tvproductdesc"
/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="#+id/imageView"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
/>
</LinearLayout>
My homepage.java contains code which is using AsyncTask to consume REST API and fill arrays of data and send it to customAdapter.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
lv=(ListView) findViewById(R.id.listView);
Bundle emailbundle=getIntent().getExtras();
email=emailbundle.get("email").toString();
initializer();
addingItemstoSpinner();
}
protected void onPostExecute(String result) {
try {
jsonArray = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
len= jsonArray.length();
pdLoading.dismiss();
if (len != 0) {
try {
String [] productIDListArr= new String[len];
String [] productNameListArr= new String[len];
String [] productDescListArr= new String[len];
String [] productImagesArr= new String[len];
String [] productStarsArr= new String[len];
for (int i=0;i<len;i++)
{
objectInArray = jsonArray.getJSONObject(i);
productIDListArr[i]=(objectInArray.getString("productId"));
productNameListArr[i]=(objectInArray.getString("productName"));
productDescListArr[i]=(objectInArray.getString("stars"));
productImagesArr[i]=(objectInArray.getString("productId"));
productStarsArr[i]=(objectInArray.getString("stars")+" out of 5");
if(i==len-1)
{
createdAt=objectInArray.getString("createdAt");
}
}
lv.setAdapter(new CustomAdapter(HomePage.this, productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr,email));
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Server is down please try again later", Toast.LENGTH_LONG).show();
}
My customAdapter.java is
package com.andapps.azaz.e_recommender;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
/**
* Created by M.Azaz on 30-Mar-17.
*/
public class CustomAdapter extends BaseAdapter {
String [] productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr;
Context context;
String email;
private static LayoutInflater inflater=null;
public CustomAdapter(HomePage homePage, String[] productIDList, String[] productNameList, String[] productDescList, String[] productImages, String[] productStars,String emailMain) {
// TODO Auto-generated constructor stub
productIDListArr=productIDList;
productNameListArr=productNameList;
productDescListArr=productDescList;
productImagesArr=productImages;
productStarsArr=productStars;
context=homePage;
email=emailMain;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return productIDListArr.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return productIDListArr[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tvproductname, tvproductid, tvproductdesc;
ImageView imageView;
RatingBar ratingBar;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.activity_custom_list, null);
holder.tvproductname=(TextView) rowView.findViewById(R.id.tvproductname);
holder.tvproductid=(TextView) rowView.findViewById(R.id.tvproductid);
holder.tvproductdesc=(TextView) rowView.findViewById(R.id.tvproductdesc);
holder.imageView=(ImageView) rowView.findViewById(R.id.imageView);
holder.ratingBar=(RatingBar) rowView.findViewById(R.id.ratingBar);
holder.tvproductname.setText(productNameListArr[position]);
holder.tvproductid.setText(productIDListArr[position]);
holder.tvproductdesc.setText(productDescListArr[position]);
holder.ratingBar.setRating(Integer.parseInt(productStarsArr[position]));
Picasso.with(context).load(context.getString(R.string.imageip) + productImagesArr[position]+".jpg").into(holder.imageView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+productIDListArr[position], Toast.LENGTH_LONG).show();
Intent intent = new Intent("com.andapps.azaz.e_recommender.RATINGS");
intent.putExtra("tag",productIDListArr[position]);
intent.putExtra("email", email);
context.startActivity(intent);
}
});
return rowView;
}
}
But when I run the code, it actually calls customAdapter.java but right after calling getCount() from customAdapter Its not calling getView and the application terminates.
One more thing... how can I update more items into existing list?
You app may crash in getCount method when productIDListArr is null. So add if condition in your getCount method before returning count.
For example :
public int getCount(){
if(productIDListArr==null){
return 0;
}else{
return productIDListArr.length;
}
}
Tips : Create a class for holding your response data and pass the list of that model class to the adapter and each time when there is any change in your data update that list and call notify method of adapter.
For example :
Class Item{
public String productIDListArr;
public String productNameListArr;
public String productDescListArr;
public String productImagesArr;
public String productStarsArr;
}
ArrayList<Item> items=new ArrayList<Item>();
for (int i=0;i<len;i++)
{
objectInArray = jsonArray.getJSONObject(i);
Item item=new Item();
item.productIDListArr=(objectInArray.getString("productId"));
.......
}
CustomAdapter extend BaseAdapter{
ArrayList<Item> items;
public CustomAdapter(ArrayList<Item> items){
this.items=items;
}
public int getCount(){
return items==null?0:items.size()
}
How i can create a custom adapter for this xml.Can someone guide me on how to create a custom adapter or give me a sample code on how to do it. Please help me i need to learn how to create custom adapter.Help me please. Thanks in advance.
This is my MainActivity.java
package com.example.work.listviewadapter;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private static final String PRODUCTLIST_URL ="http://192.168.56.1/productlist.php";
private ProgressDialog pDialog;
public static final JSONParser jParser = new JSONParser();
private static final String GET_PRODUCT = "message";
private static final String GET_ID = "ID";
private static final String GET_BRAND = "Brand";
private static final String GET_CATEGORY = "Category";
private static final String GET_DESCRIPTION = "Description";
private static final String GET_CODE = "Code";
private static final String GET_QUANTITY = "Quantity";
private static final String GET_UNIT = "Unit";
private static final String GET_UNITPRICE = "Unitprice";
private JSONArray order = null;
ListView list;
private ArrayList<HashMap<String, String>> orderlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productlist);
new LoadComments().execute();
}
public void updateJSONdata() {
orderlist = new ArrayList<HashMap<String, String>>();
JSONObject json = jParser.getJSONFromUrl(PRODUCTLIST_URL);
try {
order = json.getJSONArray(GET_PRODUCT);
for (int i = 0; i < order.length(); i++) {
JSONObject c = order.getJSONObject(i);
String id = c.getString(GET_ID);
String brand = c.getString(GET_BRAND);
String category = c.getString(GET_CATEGORY);
String description = c.getString(GET_DESCRIPTION);
String code = c.getString(GET_CODE);
String quantity = c.getString(GET_QUANTITY);
String unit = c.getString(GET_UNIT);
String unitprice = c.getString(GET_UNITPRICE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(GET_ID,id);
map.put(GET_BRAND, brand);
map.put(GET_CATEGORY, category);
map.put(GET_DESCRIPTION, description);
map.put(GET_CODE, code);
map.put(GET_QUANTITY, quantity);
map.put(GET_UNIT, unit);
map.put(GET_UNITPRICE, unitprice);
orderlist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
//this is for my custom listview
}
final public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Order...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
//we will develop this method in version 2
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
//we will develop this method in version 2
updateList();
}
}
}
This is my Custom ListView.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip"
android:background="#drawable/list_selector"
>
<TextView
android:id="#+id/Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10000"
android:textSize="24dip"
android:textStyle="bold"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="24dp"
android:layout_marginRight="51dp"
>
</TextView>
<TextView
android:id="#+id/Unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gal."
android:layout_alignParentRight="true"
android:layout_marginTop="26dp"
android:textSize="20dp"
android:layout_marginRight="15dp"
/>
<TextView
android:id="#+id/Description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="White"
android:textColor="#040404"
android:typeface="sans"
android:textSize="20dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/Code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wpu-01"
android:layout_marginTop="2dp"
android:layout_below="#+id/Description"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/Brand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Code"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:text="Weber"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Urethane"
android:layout_below="#+id/Code"
android:layout_marginTop="2dp"
android:layout_toRightOf="#+id/Brand"
android:layout_marginLeft="5dp"
android:id="#+id/Category" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Category"
android:text="P"
android:layout_marginLeft="12dp"
android:paddingRight="5dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp"
android:textStyle="italic"
android:id="#+id/P"
/>
<TextView
android:id="#+id/Price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10000.00"
android:layout_below="#+id/Brand"
android:layout_toRightOf="#+id/P"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
/>
<TextView
android:id="#+id/ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="11"
android:layout_alignParentRight="true"
android:visibility="invisible"
/>
</RelativeLayout>
This for the 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="match_parent">
<EditText
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Search"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:singleLine="true"/>
<ListView
android:layout_below="#+id/search"
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:divider="#ff5873ff"
android:dividerHeight="3dp" />
You can design your BaseAdapter like below code, also you can optimize listview performance using ViewHolder pattern
private class MyAdapter extends BaseAdapter{
private LayoutInflater mlayoutInflater;
public MyAdapter(Context context) {
mlayoutInflater = LayoutInflater.from(context); //Dynamic layout mapping
}
#Override
public int getCount() {
return orderlist.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mlayoutInflater.inflate(R.layout.listitem, null); // According to the layout of the document to instantiate view
TextView tv = (TextView)convertView.findViewById(R.id.textView);
tv.setText(orderlist.get(position).get(GET_BRAND).toString());
return convertView;
}
}
I'll use a custom adapter I've made as an example. It may solve your problem if you follow the steps and shape it to your needs.
When you want to make a custom ListView, you have to write your own adapter. In this particular case I'm subclassing the BaseAdapter class.
This custom adapter will take hold of my data model, and will inflate the data to my ListView rows.
First, I'll create the XML of my custom row. You can see the code below.
item_mail.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test text"
android:id="#+id/tv_mail"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/iv_icon"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#android:drawable/ic_menu_report_image" />
</RelativeLayout>
Here I've created a row that displays a text and an image.
Now, I'll create my custom adapter to handle this XML. As you can see below.
MailAdapter.java
public class MailAdapter extends BaseAdapter {
private static final String LOG_TAG = MailAdapter.class.getSimpleName();
private Context context_;
private ArrayList<ArrayList<String>> mailitems;
public MailAdapter(Context context, ArrayList<ArrayList<String>> mailitems) {
this.context_ = context;
this.mailitems = mailitems;
}
#Override
public int getCount() {
return mailitems.size();
}
#Override
public Object getItem(int position) {
return mailitems.get(position).get(0);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context_.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.item_mail, null);
}
TextView tv_mail = (TextView) convertView.findViewById(R.id.tv_mail);
ImageView iv_icon = (ImageView) convertView.findViewById(R.id.iv_icon);
String mail = mailitems.get(position).get(0);
String icon = mailitems.get(position).get(1);
Log.d(LOG_TAG,"Mail: " + mail + " mail_icon: " + icon);
tv_mail.setText(mail);
// iv_icon.setImageURI(); Here you can do whatever logic you want to update your image, using URI's, ID's, or something else.
return convertView;
}
}
Ok. Now we have everything to make this work. In your Activity class, do something like that:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:text="#string/hello_world"
android:id="#+id/tv_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tv_header">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add mail"
android:id="#+id/button"
android:layout_gravity="center" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView" />
</LinearLayout>
</RelativeLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
private int numMail = 1; // Dummy int to create my items with different numbers.
private MailAdapter mailAdapter; // Your custom adapter.
private ArrayList<ArrayList<String>> mailItems; // This is going to be your data structure, everytime you change it, call the notifyDataSetChanged() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.button);
ListView lv_mail = (ListView) findViewById(R.id.listView);
mailItems = new ArrayList<>();
mailAdapter = new MailAdapter(this,mailItems);
lv_mail.setAdapter(mailAdapter);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItem(); // The method I'm using to insert the item. Look for it below.
}
});
}
// Here I'm creating a new ArrayList, and appending it to my 'mailItems' Array. After that, I'm notifying the adapter that my data changed.
private void addItem() {
ArrayList<String> mail = new ArrayList<>();
mail.add(0,"mail " + numMail++);
mail.add(1,"path_to_image"); // Depending on what you want to do, put your path, URI, or whatever other way you want to store that image data.
mailItems.add(mail); // Inserting the data on the ArrayList.
mailAdapter.notifyDataSetChanged(); // Notifying the adapter that my ArrayList was modified.
}
}
This should do the trick.
You can read a little more about that here and I've found a similar question here, which you can read as well.
Edit: Another related question, which might be an interesting read.
In my application, I have grid view and I wrote a listener to get position of clicked item in the grid view. I tried many ways to solve it but it is noting working.I'm looking solutions or help I have checked everything but i'm not able to clear it.I don't know where I have done mistake. anyone help me out with is.
rowitems 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" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:background="#drawable/customborder"
android:gravity="center_vertical"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<ImageView
android:id="#+id/product_img"
android:layout_width="350dp"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:src="#drawable/ic_launcher"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_weight="0.5"
android:background="#D7D7D7" >
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="37dp"
android:text="#string/pname"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="75dp" >
<Button
android:id="#+id/product_decribe_cart"
style="?android:attr/buttonStyleSmall"
android:layout_width="75dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="46dp"
android:background="#D41A37"
android:text="#string/cart"
android:textColor="#android:color/white"
android:textSize="8dp"
android:focusable="false"
android:focusableInTouchMode="false"/>
<TextView
android:id="#+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="40dp"
android:text="#string/rate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D41A37"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="262dp"
android:layout_height="113dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="10dp"
android:background="#drawable/customborder" >
<TextView
android:id="#+id/product_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:text="Product details"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ProductActivity extends Activity
{
JSONArray results;
JSONObject jobj;
CustomProdAdapter adapter1;
ArrayList<String> a1,a2,a3,a4;
ArrayList<String> pname=new ArrayList<String>();
ArrayList<String> productdescription=new ArrayList<String>();
ArrayList<String> pimage=new ArrayList<String>();
ArrayList<String> pprice=new ArrayList<String>();
Button add;
String pid;
GridView gView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_activity);
a1=new ArrayList<String>();
a2=new ArrayList<String>();
a3=new ArrayList<String>();
a4=new ArrayList<String>();
Intent in=getIntent();
pid=in.getStringExtra("Dialoog");
System.out.println("productid"+pid);
gView = (GridView)findViewById(R.id.pa_grid);
/* gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
System.out.println("inside listener");
}
});*/
new Producttask().execute();
}
private class Producttask extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(ProductActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("my link");
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
System.out.println("---------------return product list json------------"+json);
pDialog.dismiss();
try
{
jobj=json.getJSONObject("response");
// Getting Array of Contacts
results = jobj.getJSONArray("obejects");
System.out.println("In product Activity after JSON");
// looping through All Contacts
for(int i = 0; i < results.length(); i++)
{
JSONObject c = results.getJSONObject(i);
pname.add(c.getString("product_name"));
pimage.add(c.getString("product_image"));
pprice.add(c.getString("product_price"));
productdescription.add(c.getString("Description"));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter1 = new CustomProdAdapter(getApplicationContext(), R.layout.product_describe, pname, pimage,productdescription,pprice);
gView.setAdapter(adapter1);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click"+position);
}
});
/*gv=(GridView)findViewById(R.id.product_decribe_cart);
gv.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(ProductActivity.this,product_details.class);
startActivity(i);
}
});
*/ }
}
}
Grid view listner set in oncreate method
new Producttask().execute();
gView = (GridView)findViewById(R.id.pa_grid);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click"+position);
}
});
Or set you click listener on row , like that
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row=convertView;
ViewHolder vh;
if(row==null)
{
row=inflater.inflate(R.layout.custom_product_activity, parent, false);
vh=new ViewHolder();
vh.pname=(TextView)row.findViewById(R.id.product_name);
vh.image1=(ImageView) row.findViewById(R.id.imageView1);
row.setTag(vh);
}
else
{
vh = (ViewHolder) row.getTag();
row=convertView;
}
vh.pname.setText(c_pname.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("outside on click"+"position");
}
});
return row;
}
Sorry if i am repeating the question.
I am reading SMS/s from inbox and showing them in the listview.
I can see the SMS/s in the listview as listview item after execution.
Only problem is that, the text color of listview item is vary pale.(text i am getting is not readable/visible).
I tried to change it, but nothing happened.
How i can change this color to black or to any other color ?
Here is my activity_view_task.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv_tasks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Tasks"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/lv_view_task"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_tasks"
android:layout_centerHorizontal="true"
android:cacheColorHint="#000000"
android:textColor="#000000">
</ListView>
</RelativeLayout>
Here is my java file from where I am adding the items to the listview :
package com.example.myapp;
import java.util.ArrayList;
import java.util.List;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ViewTask extends Activity {
TextView tv_view_task;
ListView lv_view_task;
static String sms = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
tv_view_task=(TextView) findViewById(R.id.tv_view_task);
lv_view_task=(ListView) findViewById(R.id.lv_view_task);
List<String> msgList = getSms();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.select_dialog_singlechoice, msgList);
lv_view_task.setAdapter(adapter);
}
public List<String> getSms() {
List<String> labeles = new ArrayList<String>();
Uri uri = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uri, null, null, null, null);
// Read the sms data and store it in the list
if (c.moveToFirst()) {
do {
String body = c.getString(c.getColumnIndex("body"));
String address = c.getString(c.getColumnIndex("address"));
sms = "From : " + address + " : " + body;
labeles.add(sms);
} while (c.moveToNext());
}
c.close();
return labeles;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_view_task, menu);
return true;
}
}
After executing it looks like this :
You will need to create a custom layout for your ListView items where you set your desired textcolor.
In this way, you do not even need a custom-adapter.
e.g. custom_textview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/tv"
android:textColor="#color/white"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_height="fill_parent"/>
</LinearLayout>
Then, you can use your layout with the ArrayAdapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.custom_textview, aa);
lv.setAdapter(adapter);
Make Custom layout name row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="HardcodedText,UselessParent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:layout_marginLeft="10dp"
android:text="Medium Text"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
Make Custom Adapter globally like:
MyAdapter adp;
now initialize it on onCreate() method:
adp = new MyAdapter (YourActivity.this, yourArrayList);
class MyAdapter extends BaseAdapter {
Context c;
String[] yourarraylist;
LayoutInflater mInflater;
public CustomAdapter(Context fullImage, String[] yourarraylist) {
// TODO Auto-generated constructor stub
this.c = fullImage;
this.yourarraylist= yourarraylist;
mInflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return yourarraylist.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_item, parent,
false);
TextView tv = (TextView) convertView.findViewById(R.id.tv);
// set text here
}
return convertView;
}
}
Add this to your activity_view_task.xml:
android:textColor="#000000"