Adding button in custom adapter class in android - android

Hi in my application I am parse the json url and displaying the image and text Now I am going to adding the button. if i click the button i want to move to another activity.Now My problem is if i click the button nothing happened .can any one please help me.
ListViewAdapter class:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView title;
ImageView thumb_url;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
title = (TextView) itemView.findViewById(R.id.rank);
// Locate the ImageView in listview_item.xml
thumb_url = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
title.setText(resultp.get(MainActivity.TITLE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.THUMB_URL), thumb_url);
// Capture ListView item click
Button Add = (Button) itemView.findViewById(R.id.add);
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("title", resultp.get(MainActivity.TITLE));
// Pass all data country
/*intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
*/// Pass all data flag
intent.putExtra("thumb_url", resultp.get(MainActivity.THUMB_URL));
// Start SingleItemView Class
context.startActivity(intent);
Intent in = new Intent(getApplicationContext(), MainActivity.class);
startActivity(in);
}
private void startActivity(Intent in) {
// TODO Auto-generated method stub
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return context;
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
return itemView;
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
listview_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/flag"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:background="#444"
android:padding="3dp" />
<TextView
android:id="#+id/rank"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_toRightOf="#+id/flag"
android:maxLines="1"
android:textSize="15dip"
android:textStyle="bold" />
<!-- <TextView
android:id="#+id/ranklabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
-->
<!-- <ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000000"
android:layout_toRightOf="#+id/flag"
android:padding="1dp" />
-->
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/rank"
android:text="Add" />
</RelativeLayout>
MainActivity class:
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String TITLE = "title";
/*static String COUNTRY = "country";
static String POPULATION = "population";*/
static String THUMB_URL = "thumb_url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunction
.getJSONfromURL("http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("veg_food");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("title", jsonobject.getString("title"));
/*map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));*/
map.put("thumb_url", jsonobject.getString("thumb_url"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}

Store the hashMap in the view tag.
Button Add = (Button) itemView.findViewById(R.id.add);
Add.setTag(resultp);
Then access it inside onClick() like this
instead of trying to access it by position which may not refer to the current view, access it by its tag. In your code, replace the line
resultp = data.get(position);
with
resultp = (HashMap<String, String>) view.getTag();
EDIT: After adding resultp = data.get(position); as shown above
Replace your onClick() with the following
#Override
public void onClick(View arg0) {
resultp = (HashMap<String, String>) view.getTag();
Intent intent = new Intent(context, SingleItemView.class);
intent.putExtra("title", resultp.get(MainActivity.TITLE));
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
intent.putExtra("thumb_url", resultp.get(MainActivity.THUMB_URL));
context.startActivity(intent);
}

Related

How do I add an event handler to a Button in Listview in Android?

My items in ListView are generated using PHP and stored in a MySQL database. How can I add an event handler function tied to the buttons? The process that I need is like this: when you click the button it will get the item and save it to other table, as well as get the current datetime also.
public class ViewBusFiveStudent extends AppCompatActivity implements ListView.OnItemClickListener {
private ListView listView;
private Button btntime;
private String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_busfour);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
}
private void showStudents(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String name = jo.getString(Config.TAG_NAME);
HashMap<String,String> student = new HashMap<>();
student.put(Config.TAG_ID,id);
student.put(Config.TAG_NAME,name);
list.add(student);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
ViewBusFiveStudent.this, list, R.layout.list_items,
new String[]{Config.TAG_ID,Config.TAG_NAME},
new int[]{R.id.id, R.id.name});
listView.setAdapter(adapter);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewBusFiveStudent.this,"Fetching Data","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showStudents();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_BUS_FOUR);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ViewBusFive.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String studId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.STUD_ID,studId);
startActivity(intent);
}
}
Here's my list_view:
<?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">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/id"/>
<CheckBox
android:id="#+id/checkBoxPres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text=""
android:layout_alignBaseline="#+id/btnTime"
android:layout_alignBottom="#+id/btnTime"
android:layout_toLeftOf="#+id/btnTime"
android:layout_toStartOf="#+id/btnTime" />
<Button
android:text="TimeStamp"
android:layout_width="105dp"
android:layout_alignParentRight="true"
android:layout_height="wrap_content"
android:id="#+id/btnTime" />
</RelativeLayout>
I just want to know how to define the function called when the button is clicked and where can i place it.
I have change the code for onitemclick, i can click the button in the listview but only one button is working/clickable.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final TextView name1 = (TextView) findViewById(R.id.name);
btnTime = (Button) findViewById(R.id.btnTime);
btnTime.setTag(position);
btnTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BusArrived();
}
public void BusArrived() {
final String name = name1.getText().toString().trim();
class SendStudent extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewBusFiveStudent.this, "Saving Dismissal Time...", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ViewBusFiveStudent.this, s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... v) {
HashMap<String, String> params = new HashMap<>();
params.put(Config.KEY_STUD_NAME, name);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Config.URL_SAVING_TO_BUS_FIVE_TIME, params);
return res;
}
}
SendStudent ae = new SendStudent();
ae.execute();
}
});
}
Please Correct my mistake here. Thanks!
Normally you set click listeners on subviews in the row layout when you bind data to the row. This happens inside the adapter. Since you are using an adapter provided by the framework, it doesn't have logic to add click listeners to buttons in your row, it only knows how to do simple bindings (e.g. strings into a TextView, etc). You will have to subclass SimpleAdapter (or something else, like BaseAdapter) and add the necessary logic yourself.
While you're at it, I suggest you switch to using RecyclerView instead of ListView. This means using RecyclerView.Adapter instead of the one you are using now, which will force you to implement the data binding logic anyway so you can add click listeners to subviews of your row layout. Also, ListView has a lot of quirks and idiosyncrasies, including weird interactions when rows have subviews that are focusable (like a clickable Button). RecyclerView will be much better for you in that regard.

Using custom array adapter

i am learning to use custom adapter and i think i am headed to the right direction until i have problem with the super method of the constructor of class Custom Adapter. Could you identify the problem behind it ?
Before that i used Simple Adapter but i want more flexibility in controlling the layout.
Here is my xml file
<?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:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!-- Name Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello This is testing"
android:id="#+id/guid"
android:visibility="gone"/>
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:text="name:"
android:textStyle="bold"
android:visibility="gone"/>
<!-- Email label -->
<TextView
android:id="#+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:text="email"
android:textStyle="bold"
/>
<!-- Mobile number label -->
<TextView
android:id="#+id/mobile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Mobile: "
android:textColor="#5d5d5d"
android:maxLines="1"/>
</LinearLayout>
here is my fragment class
public class NewsFragment extends Fragment{
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
GetNews.CustomAdapter CA;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.news, container, false);
newsList = (ListView) view.findViewById(R.id.newsListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
newsList.setOnItemClickListener(new newsListClick());
return view;
}
public class newsListClick implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SinglePost singleFrag = new SinglePost();
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings","Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
}
public View getView(int position, View convertView, ViewGroup Parent){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
HashMap<String, String> objects = new HashMap<String, String>();
TextView thisview = (TextView) convertView.findViewById(R.id.email);
thisview.setText(objects.get(position).get(POST_TITLE));
return convertView;
}
}//
}
}
Change this line
CA = new CustomAdapter(this, R.layout.list_item, postList);
to
CA = new CustomAdapter(getActivity(), R.layout.list_item, postList);
NOTE : While you are using Fragment you should use getActivity() as a Context.
Also keep in mind that you's using HashMap<String,String> so your ArrayAdapter will be ArrayAdapter<HashMap<String, String>> instead of ArrayAdapter<String>.
You are extending ArrayAdapter<String> and passing ArrayList as constructor argument. They both have to be of the same type.
Also, you need to pass Context and not your asynctask GetNews.
You could also look at BaseAdapter where you need not pass any array as constructor argument.
To expand on Piyush's answer, you will also need to modify the CustomAdapter constructor
From this:
public CustomAdapter(GetNews context, ... ) { }
to this
public CustomAdapter(Context context, ... ) { }
This is because getActivity() will return an Activity, which is an instance of the Context class - Not an instance of GetNews
private ArrayList<HashMap<String, String>> mList;
public void setmList(ArrayList<HashMap<String, String>> mList) {
this.mList = mList;
}
public CustomAdapter(Context context, int resource) {
//something is wrong with super
super(context, resource);
}
and initialize it with setting list
CA = new CustomAdapter(getActivity, R.layout.list_item);
CA.setmList(yourlist);
don't know why the super with three parameter is not working in this case but it will surely resolve your issue

Navigate to different pages when a certain LISTVIEW is clicked

I have an android project that gets the values from a remote database. I'm using a listview in eclipse and loops whatever values that my JSON have. Here is my code:
Newsfeed.java
public class NewsFeed extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://10.0.2.2/PMR_Drupal/newsfeed.php";
private static final String TAG_TITLE = "trans_name";
private static final String TAG_FOR_A = "sub_trans_name";
private static final String TAG_ACCESS_LEVEL = "ACCESS_LEVEL";
private JSONArray mComments = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsfeed);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v)
{
Intent i = new Intent("com.pallet.pts.ADDNEWSFEED");
startActivity(i);
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String trans_name = c.getString(TAG_TITLE);
String sub_trans_name = c.getString(TAG_FOR_A);
String ACCESS_LEVEL = c.getString(TAG_ACCESS_LEVEL);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, trans_name);
map.put(TAG_FOR_A, sub_trans_name);
map.put(TAG_ACCESS_LEVEL, ACCESS_LEVEL);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE, TAG_FOR_A, TAG_ACCESS_LEVEL}, new int[] { R.id.title, R.id.forApproval, R.id.count});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent("com.pallet.pts.NEWSFEED_CLICKED");
intent.putExtra("position", position);
startActivity(intent);
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewsFeed.this);
pDialog.setMessage("Checking for Updates...");
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();
}
}
}
Now my problem is, since the listview is being looped in, How do I create a listview screen with different content for each row?
Thank you in advance! :D
You need to make an activity which should be blue print for all the activity that will be invoked by ListView .You need to append some values to Intent that you'll be passed to the activity and based on this remaining component can be created dynamically .The way you are doing you will get stuck because the data are coming remote database which may vary time to time.But what I am saying to make a basic skeleton of Activity because most the component will remain same only some of the component may only change which you can add dynamically based on intent valuse
Hello based on the #Shakeeb Shaheen comment here I am trying to write a pseudo-code for you. At first create a xml layout and name it common_layout.xml which will use to show trans and subtrans name. Here is the code of this layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_trans_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_subtrans_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Create an activity for holding this layout.
Now from the NewsFeed activity you have to pass the trans name and subtrans name value when user click on the each list item. You can do this
Intent intent = new Intent(NewsFeed.this, CommonActivity.class);
intent.putExtra("TRANS_NAME", trans_name);
intent.putExtra("SUBTRANS_NAME", subtrans_name);
startActivity(intent);
And then you have to grab these value in your common activity class. This post also can help you how to pass value between two activity.

Listview not displaying data but it shows in logcat

Actually i was trying JSON parsing example and the data which is parsed but not displaying in the listview.In the logcat the data is coming ,but it is not displaying in list.
I was running using an emulator. I am not able to find the mistake.Can anyone help?
Code below shows the custom list adapter.
public class ListAdapter extends BaseAdapter{
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
Context context;
public ListAdapter(ArrayList<HashMap<String, String>> list,
Context context) {
Log.i("ListAdapter", "ListAdapter");
this.list = list;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.i("ListAdapter", "getView");
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.list, null);
}
HashMap<String, String> hashmap = new HashMap<String, String>();
TextView trank = null,tcountry = null,tpopulation = null;
ImageView image;
trank = (TextView) convertView.findViewById(R.id.rank);
tcountry = (TextView) convertView.findViewById(R.id.country);
tpopulation = (TextView) convertView.findViewById(R.id.population);
image = (ImageView) convertView.findViewById(R.id.flag);
hashmap = list.get(position);
Log.i("list", ""+list.get(position) + "hashmp " + hashmap + hashmap.get("rank"));
String rank = hashmap.get("rank").toString();
String country = hashmap.get("country").toString();
String population = hashmap.get("population").toString();
String image_url = hashmap.get("flag");
Log.i("ListAdapter", ""+rank + " "+ country + " " +population );
trank.setText(rank);
tcountry.setText(country);
tpopulation.setText(population);
return convertView;
}
}
Main activity class
public class MainActivity extends Activity {
TextView webpage,trank,tcountry,tpopulation;
ListView lv;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
String RANK = "rank";
String COUNTRY = "country";
String POPULATION = "population";
String FLAG = "flag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
trank = (TextView) findViewById(R.id.rank);
tcountry = (TextView) findViewById(R.id.country);
tpopulation = (TextView) findViewById(R.id.population);
webpage = (TextView) findViewById(R.id.webpage);
webpage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String data = getDataFromWebPage();
list = parseDataFromWeb(data);
ListAdapter adapter = new ListAdapter(list, getApplicationContext());
lv.setAdapter(adapter);
}
});
}
custom list layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="rank"
/>
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="country"
/>
<TextView
android:id="#+id/population"
android:text="population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I got solution, actually problem was with this layout file.When i removed the inner LinearLayout problem is solved.
Previously it was displayed like this after pressing the textview
But still i dont know why this layout file with inner LinearLayout doesnt work.
Make change in your code here :
#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;
}
You should return position in getItem() method:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
you have to change:
ListAdapter adapter = new ListAdapter(getApplicationContext(),list);
try this
ListAdapter adapter = new ListAdapter( MainActivity.this,list);
lv.setAdapter(adapter);
Issue was with the custom list layout.Because of the inner linear layout data was not displaying.After removing the inner layout ,it worked

GetView in BaseAdapter Calling Infinte Time

In app i am loading data from Url and displaying it in list view.Total Item which I retrieve from Url is 5 Item, Which are displayed successfully in listview.But getView() runs infinite times at backend.IT keeps on calling till activity is alive .I am unable to figure it why it is calling so much time.
My code is
public class asasa extends Activity {
//ListView listView;
Intent intent;
public int currentimageindex=0;
private ProgressDialog pDialog;
//Class Declartion DataHolder
DataHolder obj;
Timer timer;
TimerTask task;
ImageView slidingimage;
private int[] IMAGE_IDS = {
R.drawable.myno, R.drawable.cock, R.drawable.item,
R.drawable.ketchup,R.drawable.oil,R.drawable.pan
};
//ProgressDialog progressDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
static final String URL = "http://10.0.2.2/android_connect/get_all_products.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "name";
private static final String TAG_Description = "description";
private static final String TAG_URL = "url";
private static final String TAG_Price = "price";
LazyAdapter adapter;
// flag for Internet connection status
Boolean isInternetPresent = false;
// products JSONArray
JSONArray products = null;
// Connection detector class
ConnectionDetector cd;
String ITEMTITLE ="HasMapValue";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
LoadAllProducts il = new LoadAllProducts();
il.execute(URL);
}
else
{
// Internet connection is not present
// Ask user to connect to Internet
Toast.makeText(asasa.this, "No Internet Connection You don't have internet connection.", Toast.LENGTH_LONG).show();
}
}
public void longToast(CharSequence message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater=null;
private ArrayList<HashMap<String, Object>> data;
int i=0;
public LazyAdapter(Activity a, ArrayList<HashMap<String, Object>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView imageview=(ImageView) vi.findViewById(R.id.list_image);
HashMap<String, Object> song = new HashMap<String, Object>();
song = data.get(position);
DataHolder objj=new DataHolder();
objj=(DataHolder) song.get(ITEMTITLE);
Log.i("iiiiii "," " +i++);
Log.i("objj.GetName() ",objj.GetName());
Log.i("objj.GetDescription() ",objj.GetDescription());
Log.i("objj.GetPrice() ",objj.GetPrice());
title.setText(objj.GetName());
artist.setText(objj.GetDescription());
duration.setText(objj.GetPrice());
imageview.setImageBitmap(objj.Getimage());
return vi;
}
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// creating new HashMap
ArrayList<HashMap<String, Object>> productsList=new ArrayList<HashMap<String,Object>>();
Bitmap decodedByte;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(asasa.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
Log.i("products ",products.toString());
// looping through All Products
Log.i("LENGTHHHH "," "+products.length());
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
Log.i("ccccccccc ",c.toString());
// Storing each json item in variable
// String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Log.i("name::",name);
String description = c.getString(TAG_Description);
Log.i("description::",description);
String price = c.getString(TAG_Price);
Log.i("price",price);
byte[] decodedString = Base64.decode(c.getString(TAG_URL), Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
obj=new DataHolder();
obj.setData(name, description, price, decodedByte);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(ITEMTITLE, obj);
productsList.add(map);
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
ListView list;
// dismiss the dialog after getting all products
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(asasa.this, productsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
public void onPause()
{
super.onPause();
}
public class DataHolder
{
String Name;
String Description;
String Price;
Bitmap image;
public void setData(String Name,String Descipton,String Price,Bitmap iamage)
{
this.Name=Name;
this.Description=Descipton;
this.Price=Price;
this.image=iamage;
}
public String GetName()
{return Name;}
public String GetDescription()
{return Description;}
public String GetPrice()
{return Price;}
public Bitmap Getimage()
{return image;}
}
}
And getview()
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView imageview=(ImageView) vi.findViewById(R.id.list_image);
HashMap<String, Object> song = new HashMap<String, Object>();
song = data.get(position);
DataHolder objj=new DataHolder();
objj=(DataHolder) song.get(ITEMTITLE);
Log.i("iiiiii "," " +i++);
Log.i("objj.GetName() ",objj.GetName());
Log.i("objj.GetDescription() ",objj.GetDescription());
Log.i("objj.GetPrice() ",objj.GetPrice());
title.setText(objj.GetName());
artist.setText(objj.GetDescription());
duration.setText(objj.GetPrice());
imageview.setImageBitmap(objj.Getimage());
return vi;
}
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:background="#drawable/background" >
<include layout="#layout/footer" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="460dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/background2"
android:minHeight="400dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/bar" >
<Button
android:id="#+id/back"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/left" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/ImageView3_Left"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_marginTop="20dp" >
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#drawable/textarea"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
I will post the answer here for others..
When working with ListView, make sure you set a fixed height to the ListView, otherwise getView() will be called multiple times. This is because the ListView tries to calculate how many items can be visible..
and I believe I have solved the problem.
the BaseAdapter adapter requires that the listview has a high associated set to fill_parent or match_parent

Categories

Resources