I have a listview where I have 50 elements being displayed. I have decided to paginate the view so on each part of the view there are 10 elements and then a next button is clicked to get to the next 10 elements. How can i set 10 data ? I follow this article
http://rakhi577.wordpress.com/2013/05/20/listview-pagination-ex-2/
Here is my code .Can you help me with my code or a link to a guide on how to implement this correctly?
public class MainActivity extends ListActivity {
Context context;
Button btnSearch ;
EditText txtSearch;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
//loadList(0);
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//loadList(j);
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
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(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
//String address = c.getString(TAG_ADDRESS);
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected 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(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
I change the code. When i click next button[like 2,3,4,5]. showing first page data. Here is my modified code.Any help Appreciated :
public class MainActivity extends ListActivity {
private TextView title;
Context context;
Button btnSearch ;
EditText txtSearch;
private ListView listview;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
title = (TextView)findViewById(R.id.title);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position%2==0)
{
view.setBackgroundColor(Color.parseColor("#F4FA58"));
}else
{
view.setBackgroundColor(Color.parseColor("#DA81F5"));
}
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
new GetContacts().execute();
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
title.setText("Page "+(index+1)+" of "+noOfBtns);
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
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(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int number = 0;
int start = number * NUM_ITEMS_PAGE;
// looping through All Contacts
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
//for (int i = 0; i < contacts.length(); i++) {
for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected 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(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
Below is my code to show list view with pagination. There is two blue button for change pages.
You can customize according to you need.
Create UserCategory.java
package com.UserCategory;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
public class UserCategory extends Activity implements OnClickListener{
private final int PAGE_SIZE = 5;
private int StartingIndex = 0;
ArrayList<String> userClass=new ArrayList<String>();
int textlength=0;
private String lv_arr[];
private ListView lv1;
EditText searchText;
//Button Previous;
private String Machine[]={"Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12","Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12"};
ImageView next,Previous;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
searchText=(EditText)findViewById(R.id.et_Serchlist);
next=(ImageView)findViewById(R.id.btn_next);
Previous=(ImageView)findViewById(R.id.btn_previous);
next.setOnClickListener(this);
Previous.setOnClickListener(this);
//parsing();
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , Machine));
changeListViewModel(0);
}
private void changelist(int startingIndex) {
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}else if(startingIndex >= userClass.size())
startingIndex -= PAGE_SIZE;
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("ending index"+endingIndex);
if(StartingIndex!=0){
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
if(endingIndex > userClass.size()) endingIndex = userClass.size();
try {
String[] subSet = getDataSubset1(startingIndex, endingIndex);
System.out.println("subSet array"+subSet);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
} catch (Exception e) {
e.printStackTrace();
}
}
private String[] getDataSubset1(int startingIndex, int endingIndex){
String[] changeList = new String[endingIndex - startingIndex];
int index = -1;
for(int x = startingIndex; x < endingIndex; x++)
changeList[++index] = userClass.get(x);
return changeList;
}
private void changeListViewModel(int startingIndex){
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}
else if(startingIndex >= Machine.length){
startingIndex -= PAGE_SIZE;
}
System.out.println("strating"+startingIndex);
System.out.println("startingIndex"+startingIndex);
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("endingIndex"+endingIndex);
if(StartingIndex!=0)
{
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
System.out.println("ending index"+endingIndex);
if(endingIndex > Machine.length) {
endingIndex = Machine.length;
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
String[] subSet = getDataSubset(startingIndex, endingIndex);
System.out.println("subSet main array"+subSet.length);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
}
private String[] getDataSubset(int startingIndex, int endingIndex){
String[] toRet = new String[endingIndex - startingIndex];
int index = -1;
System.out.println("index"+index);
for(int x = startingIndex; x < endingIndex; x++)
toRet[++index] = Machine[x];
return toRet;
}
private void parsing() {
// TODO Auto-generated method stub
try {
URL url = new URL("http://10.10.1.100/DogEventsWebService/EventService.svc/categories/1");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("UserCategory");
Machine = new String[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
Machine[i] = new String();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("ClassDescription");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Machine[i]=((Node) nameList.item(0)).getNodeValue();
}
System.out.println("after for loop Machine"+Machine);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_next:
textlength=searchText.getText().length();
System.out.println("nextbutton"+textlength);
if(textlength==0){
changeListViewModel(StartingIndex + PAGE_SIZE);
}else{
changelist(StartingIndex + PAGE_SIZE);
}
break;
case R.id.btn_previous:
textlength=searchText.getText().length();
if(textlength==0){
changeListViewModel(StartingIndex - PAGE_SIZE);
}else{
changelist(StartingIndex - PAGE_SIZE);
}
break;
default:
break;
}
}
}
create main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<View android:layout_height="35dp"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<TextView android:id="#+id/tv_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:layout_alignParentTop="true"
android:layout_marginLeft="0dp"
android:textSize="25dp"/>
<EditText
android:id="#+id/et_Serchlist"
android:layout_height="35dp"
android:paddingLeft="19dp"
android:layout_marginLeft="60dp"
android:layout_toRightOf="#+id/tv_header"
android:maxLength="20"
android:maxLines="1"
android:inputType="text"
android:hint="Search"
android:textColor="#ffffff"
android:background="#drawable/my_border"
android:layout_width="100dip"/>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:textSize="4px"
android:layout_below="#+id/tv_header"
android:layout_above="#+id/btn_previous"
android:layout_height="wrap_content" />
<View android:layout_height="55dp"
android:layout_below="#+id/ListView0"
android:layout_alignParentBottom="true"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<ImageView
android:src="#drawable/grewprevious"
android:id="#+id/btn_Whiteprevious"
android:layout_width="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/right"
android:id="#+id/btn_grewforward"
android:layout_width="wrap_content"
android:layout_marginLeft="259dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/backward"
android:id="#+id/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:onClick="backButtonClicked"/>
<ImageView android:src="#drawable/forward"
android:id="#+id/btn_next"
android:layout_width="80dp"
android:layout_marginBottom="6dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/ListView0"
android:layout_marginLeft="249dp"
android:text="Next"
android:onClick="nextButtonClicked"/>
</RelativeLayout>
Create userlist.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">
<TextView android:id="#+id/tv_className"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
Add my_border.xml into Drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dip" android:color="#ee777777" />
<solid android:color="#ee444444"/>
<padding
android:left="20dip"
android:top="2dip"
android:right="20dip"
android:bottom="2dip" />
<corners android:radius="15dip" />
![enter image description here][1]</shape>
If it give error for iamges then use any other images and run application.
Let me know it work for you.
Thanks
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to select the first index in listview on first load onCreate. I've try the listView.setSelection(0) but some error occur. this is my code...
public class QandAPractice extends AppCompatActivity {
String qsid;
ListView listView;
ArrayList<String> myqid;
RadioButton r1,r2,r3,r4;
String txtcontent, txtTimer,txtAnskey,txtImg, txtA, txtB, txtC, txtD, txtID;
private static final String TAG_QID = "id";
private static final String TAG_TITLE = "content";
private static final String TAG_TIMER = "timer";
private static final String TAG_IMAGE = "images";
private static final String TAG_QSID = "qsid";
private static final String TAG_KEY = "key";
private static final String TAG_A = "A";
private static final String TAG_B = "B";
private static final String TAG_C = "C";
private static final String TAG_D = "D";
ArrayList<HashMap<String, String>> questions;
Dialog quizDialog;
public int i = 60;
public int loadindex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qand_apractice);
questions = new ArrayList<>();
myqid = new ArrayList<>();
Bundle b = getIntent().getExtras();
setTitle(b.getString("subject"));
qsid = b.getString("qsid");
quizDialog = new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
listView = findViewById(R.id.lvquestions);
getJSON(Constants.ROOT_URL+"mobile_question_index.php?qsid="+qsid);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
txtID = ((TextView) view.findViewById(R.id.quiz_id)).getText()
.toString();
txtcontent = ((TextView) view.findViewById(R.id.quiz_content)).getText()
.toString();
txtTimer = ((TextView) view.findViewById(R.id.quiz_timer)).getText()
.toString();
txtAnskey = ((TextView) view.findViewById(R.id.quiz_key)).getText()
.toString();
txtA = ((TextView) view.findViewById(R.id.quiz_A)).getText()
.toString();
txtB = ((TextView) view.findViewById(R.id.quiz_B)).getText()
.toString();
txtC = ((TextView) view.findViewById(R.id.quiz_C)).getText()
.toString();
txtD = ((TextView) view.findViewById(R.id.quiz_D)).getText()
.toString();
txtImg = ((TextView) view.findViewById(R.id.quiz_image)).getText()
.toString();
showQuiz();
}
});
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
}
this is the Error fetch in debug logcat..
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setSelected(boolean)' on a null object reference
at com.example.jhan08.engineeringexclusivereviewer.QandAPractice.onCreate(QandAPractice.java:90)
at android.app.Activity.performCreate(Activity.java:6351)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1114)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2470)
I've read some thread that has the same issue like mine. They use adapter to fix the issue but still in my case this error still occur. Any help is much appreciated.
Do Your Selection after you set Your Adapter to the Listview
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
I think I got the main issue you have faced. You try to select an item before populating the list view. You need to set this after adapter added on the listview.
Add this lines after adding the adapter.
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
or use
listView.setAdapter(adapter);
listView.setItemChecked(0, true)
This will show a toast message for first opening. This should be added after the adapter set.
Iterator myVeryOwnIterator = questions.get(0).keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String value=(String)meMap.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
I am trying to post data to mysql data base and it post it. But now i am trying to apply check if the fields in activity are empty - and data isn't posted to database.
public class Accepter extends Activity implements OnClickListener{
private EditText etName,etAge,etCity,etContact,etQuantity;
private Spinner spBloodGroup;
private ImageView imCancel,imSave;
private String message = "POST";
private static String[] BLOOD_GROUPS = {"Select Blood Group","A +Ve","B +Ve","AB +Ve","O +Ve","A -Ve","B -Ve","AB -Ve","O -Ve"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.accepter_entry_form);
etName = (EditText)findViewById(R.id.etNameAcc);
etAge = (EditText)findViewById(R.id.etAgeAcc);
etCity = (EditText)findViewById(R.id.etCityAcc);
etContact = (EditText)findViewById(R.id.etPhoneNoAcc);
etQuantity = (EditText)findViewById(R.id.etQuantityAcc);
spBloodGroup = (Spinner)findViewById(R.id.spBloodGroupAcc);
imCancel = (ImageView)findViewById(R.id.imCancelAcc);
imSave = (ImageView)findViewById(R.id.imSaveAcc);
imCancel.setOnClickListener(this);
imSave.setOnClickListener(this);
ArrayAdapter<String> bgAdapter = new ArrayAdapter<String>(Accepter.this,android.R.layout.simple_spinner_item,BLOOD_GROUPS);
bgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spBloodGroup.setAdapter(bgAdapter);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.imSaveAcc:
String name = etName.getText().toString();
String blood = spBloodGroup.getSelectedItem().toString();
String quantity = etQuantity.getText().toString();
String phone = etContact.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String city = etCity.getText().toString();
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month= c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(day) + "-" + String.valueOf(month) + "-" + String.valueOf(year);
if(name.length()>1 && blood.length()>1 && phone.length()>1 && age>15 && city.length()>1)
{
AccepterTask task = new AccepterTask(v.getContext());
task.execute(message ,name, blood, phone, String.valueOf(age),city,quantity,date);
etName.setText("");
spBloodGroup.setSelection(0);
etContact.setText("");
etAge.setText("");
etCity.setText("");
etQuantity.setText("");
finish();
}
else
{
Toast.makeText(Accepter.this, "Any field is empty or invalid", Toast.LENGTH_LONG).show();
}
break;
case R.id.imCancelAcc:
Intent i = new Intent(v.getContext(),MainView.class);
i.putExtra("type", "Accepter");
startActivity(i);
break;
}
}
public class AccepterTask extends AsyncTask<String, Void, String>{
private Context context;
private JSONParser jsonParser = new JSONParser();
private JSONObject json;
private String accepter_url = //"http://192.168.0.6/accepter.php";
"http://10.0.2.2/accepter.php";
private String s;
public AccepterTask(Context c)
{
context = c;
}
#Override
protected String doInBackground(String... params)
{
String message = params[0];
if(message.equals("POST"))
{
List<NameValuePair> list = new ArrayList<NameValuePair>();
final String names = params[1];
final String blood = params[2];
final String phone = params[3];
final String age = params[4];
final String city = params[5];
final String quantity = params[6];
final String date = params[7];
list.add(new BasicNameValuePair("name", names));
list.add(new BasicNameValuePair("blood", blood));
list.add(new BasicNameValuePair("quantity", quantity));
list.add(new BasicNameValuePair("phone", phone));
list.add(new BasicNameValuePair("age", age));
list.add(new BasicNameValuePair("city", city));
list.add(new BasicNameValuePair("date", date));
json = jsonParser.makeHttpRequest(accepter_url, params[0], list);
}
try
{
s = json.getString("message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String result)
{
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}
here for updates
I had query title column from database and want to set it in TextView in GridView.
How?
CafeDatasource
public List<Model_Insert> findTblCafe(){
List<Model_Insert> model_Inserts = new ArrayList<Model_Insert>();
Cursor cursor = database.query(CafeDbOpenHelper.TABLE_CAFE, rtv_tbl_Cafe,
null, null, null, null, null);
Log.i("number", "return" + cursor.getCount()+ " rows");
if(cursor.getCount() > 0){
while (cursor.moveToNext()) {
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ID)));
model_Insert.setCafe_Title(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_TITLE)));
model_Insert.setCafe_Been(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_BEEN)));
model_Insert.setCafe_Want(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WANT)));
model_Insert.setCafe_Address(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ADDRESS)));
model_Insert.setCafe_Thumb(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_THUMB)));
model_Insert.setCafe_Description(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_DESCRIPTION)));
model_Insert.setCafe_WifiRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WIFI_RATE)));
model_Insert.setCafe_CoffeeRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_COFFEE_RATE)));
model_Insert.setCafe_Latitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LATITUDE)));
model_Insert.setCafe_Longitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LONGITUDE)));
model_Inserts.add(model_Insert);
}
}
return model_Inserts;
}
MainActivity
public ArrayList<HashMap<String, String>> placeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
===============================================================
dataSource = new CafeDataSource(this);
dataSource.open();
List<Model_Insert> model_Inserts = dataSource.findTblCafe();// query database (findTblCafe)
if(model_Inserts.size() == 0){
new DownloadImageTask().execute();
model_Inserts = dataSource.findTblCafe();
}
===============================================================
} // End onCreate
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList));
}
public class DownloadImageTask extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
placeList = new ArrayList<HashMap<String,String>>();
JSONParser jParser = new JSONParser();
JSONObject jsonO = jParser.getJSONUrl(url);
try {
places = jsonO.getJSONArray("place");
for (int i = 0; i < places.length(); i++) {
JSONObject jobj = places.getJSONObject(i);
int cafe_id = jobj.getInt(TAG_CAFE_ID);
String cafe_title = jobj.getString(TAG_CAFE_TITLE);
int cafe_been = jobj.getInt(TAG_CAFE_BEEN);
int cafe_want = jobj.getInt(TAG_CAFE_WANT);
String cafe_address = jobj.getString(TAG_CAFE_ADDRESS);
String cafe_thumb = jobj.getString(TAG_CAFE_THUMB);
String cafe_description = jobj.getString(TAG_CAFE_DESCRIPTION);
int cafe_wifi_rate = jobj.getInt(TAG_CAFE_WIFI_RATE);
int cafe_coffee_rate = jobj.getInt(TAG_CAFE_COFFEE_RATE);
double cafe_latitude = jobj.getDouble(TAG_CAFE_LATITUDE);
double cafe_longitude = jobj.getDouble(TAG_CAFE_LONGITUDE);
// Table Save
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert = dataSource.createTableCafeSave(model_Insert);
Log.i("data", " ID " + model_Insert.getCafe_Id());
// Table Cafe
model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Title(cafe_title);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert.setCafe_Address(cafe_address);
model_Insert.setCafe_Thumb(cafe_thumb);
model_Insert.setCafe_Description(cafe_description);
model_Insert.setCafe_WifiRate(cafe_wifi_rate);
model_Insert.setCafe_CoffeeRate(cafe_coffee_rate);
model_Insert.setCafe_Latitude(cafe_latitude);
model_Insert.setCafe_Longitude(cafe_longitude);
model_Insert = dataSource.createTableCafe(model_Insert);
Log.i("data", " Picture " + model_Insert.getCafe_Id());
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CAFE_TITLE, cafe_title);
placeList.add(map);
}
// for " piture " Object in json
pictures = jsonO.getJSONArray("pictures");
for (int i = 0; i < pictures.length(); i++) {
JSONObject jObj = pictures.getJSONObject(i);
int cafe_id = jObj.getInt(TAG_CAFE_ID);
String picture_url = jObj.getString(TAG_PICTURE_URL);
// Table Picture
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setPitureUrl(picture_url);
model_Insert = dataSource.createTablePicture(model_Insert);
Log.i("pic", " Picture " + model_Insert.getPitureurl());
HashMap<String, String> map = new HashMap<String, String>();
placeList.add(map);
}
} catch (JSONException e) {
// TODO: handle exception
}
return null;
}
protected void onPostExecute(Void unused) {
ShowAllContent(); // When Finish Show Content
}
}
private static class ViewHolder {
public ImageView imageview;
public TextView txtTitle;
}
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String,String>>();
public ImageAdapter(Context c, ArrayList<HashMap<String, String>> myArrayList){
context = c;
MyArr = myArrayList;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View converView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(converView == null){
converView = inflater.inflate(R.layout.grid_item, null);
}
viewHolder.imageview = (ImageView) converView.findViewById(R.id.imv_card_cafe);
viewHolder.txtTitle = (TextView) converView.findViewById(R.id.txt_title);
/* String str = "frute : juse text";
Integer len;
len = str.length();
if(len > 20){
String result = str.substring(0, 15);
viewHolder.txtTitle.setText(result);
}
else {
viewHolder.txtTitle.setText(str);
} */
=============================================================================
viewHolder.txtTitle.setText(...............................?);
=============================================================================
viewHolder.imageview.setImageResource(mThumb[position]);
return converView;
}
}
because you are getting all titles inside model_Inserts List you will need to pass this List to Custom BaseAdapter for showing in TextView as :
Change ShowAllContent() method as:
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList,model_Inserts));
}
and ImageAdapter constructor as :
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr =
new ArrayList<HashMap<String,String>>();
List<Model_Insert> model_Inserts=null;
public ImageAdapter(Context c,
ArrayList<HashMap<String, String>> myArrayList,
List<Model_Insert> model_Inserts){
context = c;
MyArr = myArrayList;
this.model_Inserts=model_Inserts;
}
///your code here...
now use model_Inserts for getting Title to show inside getView
I have a custom gridVIew With an ImageView and a TextView in it, and I have set the gridView as a it show 2 coloumns. here is the code of custom_grid_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget44"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="#+id/imgBookCover"
android:layout_width="88dp"
android:layout_height="102dp"
android:adjustViewBounds="true"
android:background="#drawable/rounded_image_borders"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:src="#drawable/book5" >
</ImageView>
<TextView
android:id="#+id/txt_BookTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_horizontal"
android:lines="1"
android:text="TextView"
android:textColor="#color/White"
android:textColorHighlight="#656565" >
</TextView>
and here is the layout of gridview.xml
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_below="#+id/Rel_Spinner"
android:layout_centerHorizontal="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
Its loading the images from server and showing the correct images and text for the first time, as I have implemented the EndlessScrollListner class in my project.
In the first itration im loading 12 images from the server, when i Scroll down the gridView to end it sends the second request to Load 12 more images and text from the server.
Here the actual problem starts its loading the same images and text.
Please have a look on my bulky code and tell where I am commeting the mistake.
public class Home extends Activity {
static final String URL = "http://www.shiaislamiclibrary.com/requesthandler.ashx";
static final String KEY_ITEM = "Book"; // parent node
static final String KEY_BOOKAUTHOR = "book_author";
static final String KEY_BOOKRATING = "BookRating";
static final String KEY_BOOKID = "BookID";
static final String KEY_BOOKDESC = "BookDescription";
static final String KEY_BOOKDATEPUBLISHED = "DatePublished";
static final String KEY_BOOKTITLE = "BookTitle";
static final String KEY_BOOKCODE = "BookCode";
static final String KEY_BOOKIMAGE = "BookImage";
static final String KEY_ITEM_BOOKs_LIMIT = "Result"; // parent node
static final String KEY_ITEM_TOTAL_BOOKS = "TotalBooks";
static ArrayList<String> BookTitle = null;
static ArrayList<Integer> BookRating = null;
static ArrayList<String> BookDescription = null;
static ArrayList<String> BookCoverPhotos = null;
static ArrayList<String> BookAuther = null;
static ArrayList<String> BookIDs = null;
static ArrayList<String> BookCode = null;
static ArrayList<String> BookPublishDate = null;
static ArrayList<String> ImageByte = null;
static ArrayList<Bitmap> bitmapArray = null;
static int initialIndex = 12;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
gridView = (GridView) findViewById(R.id.gridview);
gridView.setOnScrollListener(new EndlessScrollListener());
if (BookTitle == null) {
BookTitle = new ArrayList<String>();
BookRating = new ArrayList<Integer>();
BookDescription = new ArrayList<String>();
BookIDs = new ArrayList<String>();
BookCode = new ArrayList<String>();
BookCoverPhotos = new ArrayList<String>();
BookAuther = new ArrayList<String>();
BookPublishDate = new ArrayList<String>();
ImageByte = new ArrayList<String>();
bitmapArray = new ArrayList<Bitmap>();
new UIThread().execute(URL, initialIndex + "");
// Log.i("If", BookTitle + "");
} else {
// Log.i("else", BookTitle + "");
ImageAdapter adapter2 = new ImageAdapter(getBaseContext(),
act);
gridView.setAdapter(adapter2);
}
Im using AsynkTaks to download the images from server. here is the code
private class UIThread extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
ImageAdapter adapter = new ImageAdapter(getBaseContext(), act);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getParent(),
"Acumlating Books from server...",
"This may Take a few seconds.\nPlease Wait...");
}
#Override
protected String doInBackground(String... params) {
String URL = params[0];
int initialIndex = Integer.valueOf(params[1]);
Log.i("params", params[1] + "");
XMLParser parser = new XMLParser();
String XMLString = parser.getXmlFromUrl_FeaturedBooks(URL,
initialIndex);
Home.initialIndex = Home.initialIndex + 12;
Log.i("Home.initialIndex", Home.initialIndex + "");
Document doc = parser.getDomElement(XMLString);
NodeList nlBooksLimit = doc
.getElementsByTagName(KEY_ITEM_BOOKs_LIMIT);
Element eLimit = (Element) nlBooksLimit.item(0);
String totalBooks = parser.getValue(eLimit, KEY_ITEM_TOTAL_BOOKS);
Log.i("totalBooks", totalBooks + "");
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
Bitmap imageNotFound = BitmapFactory.decodeResource(getResources(),
R.drawable.defaultcoverphoto);
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
try {
BookRating.add(Integer.valueOf(parser.getValue(e,
KEY_BOOKRATING)));
// Log.i("Rating Try", BookRating.get(i) + "");
} catch (Exception e2) {
BookRating.add(0);
// Log.i("Rating Catch", BookRating + "");
}
BookDescription.add(parser.getValue(e, KEY_BOOKDESC));
BookTitle.add(parser.getValue(e, KEY_BOOKTITLE));
BookCoverPhotos.add("http://shiaislamicbooks.com/books_Snaps/"
+ parser.getValue(e, KEY_BOOKCODE) + "/1_thumb.jpg");
BookAuther.add(parser.getValue(e, KEY_BOOKAUTHOR));
BookPublishDate.add(parser.getValue(e, KEY_BOOKDATEPUBLISHED));
BookIDs.add(parser.getValue(e, KEY_BOOKID));
BookCode.add(parser.getValue(e, KEY_BOOKCODE));
// Log.i("URLs & Desc", BookCoverPhotos.toString());
try {
bookImageURL = new URL(BookCoverPhotos.get(i));
} catch (MalformedURLException e1) {
e1.printStackTrace();
// Log.i("URL", "ERROR at image position" + i + "");
}
try {
bitMapImage = BitmapFactory.decodeStream(bookImageURL
.openConnection().getInputStream());
bitmapArray.add(bitMapImage);
publishProgress(i + 1);
} catch (IOException e2) {
e2.printStackTrace();
bitmapArray.add(imageNotFound);
// Log.i("File Not Found", bookImageURL + "");
}
}
Log.i("Book Title", BookTitle + "");
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setMessage(values[0]
+ " Book(s) found \nPlease wait...");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
gridView.setAdapter(adapter);
}
}
and here is the EndlessScrollListner.java code. which send the request to sever again to download when the scroll reaches to the bottom of the gridView.
private class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new UIThread().execute(URL, Home.initialIndex + "");
Log.i("Reached", "End");
Log.i("Home.initialIndex", Home.initialIndex + "");
loading = true;
}
}
here are 2 pictures to make you more clear my question.
Although pretty late, but I just ran into the same problem. Its happening because of the adapter's getView method.
In your ImageAdapter, if the getView function reuses the view already created then this might be the reason for your image repetition. If the code looks like below, then it is supposed to be changed like the second code snippet to download new images coming from load more.
Snippet 1
public View getView(int position, View v, ViewGroup parent) {
ImageView imageview;
if(v == null)
{
imageview = new ImageView(mcontext);
imageview.setLayoutParams(new GridView.LayoutParams(250,250));
imageview.setPadding(0,0,10,10);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
new DownloadImageTask(imageview).execute(arr.get(position).imageUrl);
}
else
imageview = (ImageView) v;
return imageview;
}
Snippet 2
public View getView(int position, View v, ViewGroup parent) {
ImageView imageview;
if(v == null)
{
imageview = new ImageView(mcontext);
imageview.setLayoutParams(new GridView.LayoutParams(250,250));
imageview.setPadding(0,0,10,10);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
else
imageview = (ImageView) v;
new DownloadImageTask(imageview).execute(arr.get(position).imageUrl);
return imageview;
}
Or probably create a new view altogether but then you may need to handle virtualization and reusability of the gridView/listView by yourself.
i have an app that is showing data in listview ,but i want first row to be inflated by diferent layout , and i did that but since there is gona be a big number of listitems , i want to optimize listview and there is issue. i cant optimize listview when iam filling listview on that way , so how can i put content that should go in fist row inside listview header witch is inflated by some layout ,here is the code of Adapter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
refLayout.setVisibility(View.GONE);
mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
mBtnNaslovnica.setSelected(true);
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
loadPage();
ImageButton mBtnRefresh = (ImageButton) findViewById(R.id.btnRefresh);
mBtnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoadingTask().execute(URL);
}
});
}
public void loadPage(){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(getIntent().getStringExtra("json"));
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void reloadPage(String jsonstring){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(jsonstring);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void startNewActivity(){
}
public class LoadingTask extends AsyncTask<String, Object, Object>{
XMLParser parser = new XMLParser();
JSONParser jParser = new JSONParser();
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
protected void onPreExecute(){
content.setClickable(false);
refLayout.setVisibility(View.VISIBLE);
}
#Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = params[0];
JSONObject json = jParser.getJSONFromUrl(URL);
//String xml = parser.getXmlFromUrl(URL); // getting XML from URL
// getting DOM element
return json;
}
protected void onPostExecute(Object result){
String json;
json = result.toString();
reloadPage(json);
refLayout.setVisibility(View.GONE);
}
}
}
If I got your point - you can go with 2 approaches:
Add headerView to the list. That is just easy as inflate your View and pass it to
addHeaderView(View) of your List. Note: you must add this view before setting the adapter, or it will throw the exception.
However, as your 'header' is representing the same data as all other items, but has different layout - I suggest not to use Header here. Instead, try to implement getItemViewType() in your adapter. http://developer.android.com/reference/android/widget/BaseAdapter.html#getItemViewType(int)
If you'll do - you'll have ability to check which type of layout to return in getView() method. And Android will take care of optimizing and reusing your inflated Views for you, so you can be sure that convertView, passed to your getView will be of the right type and layout.
Please let me know if I should explain with more details.
You can do it like this:
...
convertView.setOnClickListener(new OnItemClick(position));
...
public class OnItemClick implements OnClickListener {
private final int index;
public OnItemClick(int _index) {
this.index = _index;
}
#Override
public void onClick(View v) {
//dosomething
}
}