How to populate partial Data into ListView - android

Still i am populating all JSON data into ListView, but now i want to populate (records into ListView) based on visibility, when user scrolls I want to show progess bar for 5 seconds and then want to populate more records (those will be visible to user) and so on...
I don't want to populate all data into ListView for the first time !
MainActivity.java:
public class MainActivity extends Activity {
ArrayList<Main> arrayList;
MainAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<Main>();
new JSONAsyncTask().execute("....");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new MainAdapter(getApplicationContext(), R.layout.row, arrayList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), arrayList.get(position).getTitle(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Main main = new Main();
main.setTitle(object.getString("title"));
Log.v("title:", object.getString("title"));
arrayList.add(main);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
MainAdapter.java:
public class MainAdapter extends BaseAdapter {
ArrayList<Main> arrayList;
LayoutInflater layoutInflater;
int resource;
ViewHolder viewHolder;
public MainAdapter(Context context, int resource, ArrayList<Main> arrayList) {
this.layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resource = resource;
this.arrayList = arrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View view = convertView;
if (view == null) {
viewHolder = new ViewHolder();
view = layoutInflater.inflate(resource, null);
viewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tvName.setText(arrayList.get(position).getTitle());
return view;
}
static class ViewHolder {
public TextView tvName;
}
}

You can try using this library (Android-Infinite-Scroll-Listview)
I've used it before and it's easy to work with.

Related

setting onClickListener on listView that is populated with json

i have implemented a multi colum list view that is populated from json data. i also have set an onClickListener to it. but on running the app when i click the listView i am only able to fetch the first item of the list.
what i want to acheive is when i click on any item in the listView i should be able to get the row item. the code that i used is as follows
Adapter.java
private Activity activity;
private static ArrayList prefrenceid,partnerid;
private static LayoutInflater inflater = null;
public CompanyRegistrationAdapter(Activity a, ArrayList pref, ArrayList part) {
activity = a;
this.prefrenceid = pref;
this.partnerid=part;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return prefrenceid.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.company_registation_adapter, null);
TextView preferences = (TextView) vi.findViewById(R.id.textView20);
String song = prefrenceid.get(position).toString();
preferences.setText(song);
TextView partner = (TextView) vi.findViewById(R.id.textView21);
String song2 = partnerid.get(position).toString();
partner.setText(song2);
return vi;
}
MainActivity.java
AsyncHttpClient usercheck = new AsyncHttpClient();
usercheck.get("REST URL", new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
try {
progressDialog.hide();
JSONObject obj3 = new JSONObject(response);
final JSONArray jsonArray3 = obj3.getJSONArray("REST Method");
int length3 = jsonArray3.length();
if (length3 != 0) {
for (int i = 0; i < length3; i++) {
JSONObject user3 = jsonArray3.getJSONObject(i);
preference_array.add(user3.getString("GCP_NUMBER").toString());
partner_array.add(user3.getString("COMPANY_NAME").toString());
}
adapter = new CompanyRegistrationAdapter(CompanyRegistrationResult.this, preference_array, partner_array);
fav.setAdapter(adapter);
fav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
String iPartnerID = jsonArray3.getJSONObject(position).getString("ID");
Toast.makeText(getApplicationContext(),iPartnerID,Toast.LENGTH_SHORT).show();
Intent compRegister=new Intent(getApplicationContext(),CompanyRegistration.class);
compRegister.putExtra("gcp", gcp);
compRegister.putExtra("compName", compName);
startActivity(compRegister);
} catch (JSONException e) {
e.printStackTrace();
}
String gcp=((TextView) findViewById(R.id.textView20)).getText().toString();
String compName=((TextView) findViewById(R.id.textView21)).getText().toString();
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

onitemclick does not work in fragment (custom list view)

I have created an activity to get and show data to a custom list view.
Now I have changed this to fragment but onItemclick does not work.
SiteNews.java
public class SiteNews extends Fragment implements OnTabChangeListener,
OnPageChangeListener {
private TabHost tabHost;
private ViewPager viewPager;
private FragmentPagerNewsAdapter fragmentPagerNewsAdapter;
int i = 0;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.tabs_news_layout, container, false);
// put tabhost here:
// ***************************** part 1
// ***************************************************
i++;
// init tabhost
this.initializeTabHost(savedInstanceState);
// init ViewPager
this.initializeViewPager();
// ***************************** part 1
// ***************************************************
return v;
}
private void initializeViewPager() {
List<Fragment> fragmentsnews = new Vector<Fragment>();
fragmentsnews.add(new FragmentAllNews());
fragmentsnews.add(new FragmentUnreadNews());
this.fragmentPagerNewsAdapter = new FragmentPagerNewsAdapter(
getChildFragmentManager(), fragmentsnews);
this.viewPager = (ViewPager) v.findViewById(R.id.viewPagernews);
this.viewPager.setAdapter(this.fragmentPagerNewsAdapter);
this.viewPager.setOnPageChangeListener(this);
}
// fake content for tabhost
class FakeContent implements TabContentFactory {
private final Context mContext;
public FakeContent(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
private void initializeTabHost(Bundle args) {
tabHost = (TabHost) v.findViewById(android.R.id.tabhost);
tabHost.setup();
for (int i = 1; i <= 2; i++) {
TabHost.TabSpec tabSpec;
tabSpec = tabHost.newTabSpec("Tab " + i);
tabSpec.setIndicator("Tab " + i);
tabSpec.setContent(new FakeContent(getActivity()));
tabHost.addTab(tabSpec);
}
tabHost.setOnTabChangedListener(this);
}
#Override
public void onTabChanged(String tabId) {
int pos = this.tabHost.getCurrentTab();
this.viewPager.setCurrentItem(pos);
HorizontalScrollView hScrollView = (HorizontalScrollView) v
.findViewById(R.id.hScrollViewnews);
View tabView = tabHost.getCurrentTabView();
int scrollPos = tabView.getLeft()
- (hScrollView.getWidth() - tabView.getWidth()) / 2;
hScrollView.smoothScrollTo(scrollPos, 0);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
this.tabHost.setCurrentTab(position);
}
}
FragmentAllnews.java
public class FragmentAllNews extends Fragment implements View.OnClickListener {
ViewGroup v;
ListView list;
CustomAdapterAllNews adapter;
JSONObject json_data;
JSONArray jArray;
NewsGetData newsGetData;
ArrayList<String> id, title_news, text_news, cat_id, status;
String data, url, msg, check, readnumber, ACTION_SCAN, contents;
ArrayList<News> newsha;
News n;
int sizearray;
Resources res;
ArrayList<News> items;
News ne;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = (ViewGroup) inflater.inflate(R.layout.tabfragmentallnews,
container, false);
list = (ListView) v.findViewById(R.id.listallnews);
res = getResources();
createarray();
/* items = new ArrayList<News>();
for (int k = 0; k < 25; k++) {
ne = new News();
ne.setTitle_news("title_news " + String.valueOf(k));
ne.setText_news("text_news " + String.valueOf(k));
ne.setCat_id(k);
ne.setStatus(k);
items.add(ne);
}*/
ReadData task1 = new ReadData();
task1.execute(new String[] { "url address" });
return v;
}
private void createarray() {
id = new ArrayList<String>();
title_news = new ArrayList<String>();
text_news = new ArrayList<String>();
cat_id = new ArrayList<String>();
status = new ArrayList<String>();
id.clear();
title_news.clear();
text_news.clear();
cat_id.clear();
status.clear();
}
private class ReadData extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
dialog.setMessage("Reading Data...");
dialog.show();
}
String text = "";
ArrayList<String> list1;
#Override
protected Boolean doInBackground(String... urls) {
url = "php url address";
InputStream is1;
for (String url1 : urls) {
// Read from web to InputStream
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// HttpPost post = new HttpPost(url1);
HttpResponse response = client.execute(post);
is1 = response.getEntity().getContent();
} catch (ClientProtocolException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
} catch (IOException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
}
// end of Read from web to InputStream
// Convert from InputStream to String Text
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(is1,
"iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
is1.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from InputStream to String Text
// Convert from Text to JSON and add to ArrayList list1
list1 = new ArrayList<String>();
try {
JSONArray jArray = new JSONArray(text);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonData = jArray.getJSONObject(i);
list1.add(jsonData.getString("title_news") + " - "
+ jsonData.getString("text_news"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from Text to JSON and add to ArrayList list1
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if (result == true) {
// add list1 to ArrayAdapter
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1,
list1);
// set adapter into listStudent
// list.setAdapter(adapter1);
Toast.makeText(getActivity(), text, Toast.LENGTH_LONG).show();
data = text;
newsha = parseJSON3(data);
adddata(newsha);
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG)
.show();
}
dialog.dismiss();
}
}
/*
* #Override public void onItemClick(AdapterView<?> parent, View
* clickedView, int pos, long id) { TextView tv1 = (TextView)clickedView;
* int commaIndex = tv1.getText().toString().indexOf(","); String st_id =
* tv1.getText().toString().substring(0, commaIndex);
*
* Intent in = new Intent(this, EditDataActivity.class);
* in.putExtra("st_id", st_id); startActivity(in);
*
* }
*/
public void onItemClick(int mPosition) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
public ArrayList<News> parseJSON3(String result) {
ArrayList<News> userha = new ArrayList<News>();
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
n = new News();
n.setId(json_data.getInt("id"));
id.add(String.valueOf(json_data.getInt("id")));
n.setTitle_news(json_data.getString("title_news"));
title_news.add(json_data.getString("title_news"));
n.setText_news(json_data.getString("text_news"));
text_news.add(json_data.getString("text_news"));
n.setCat_id(json_data.getInt("cat_id"));
cat_id.add(String.valueOf(json_data.getInt("cat_id")));
n.setStatus(json_data.getInt("status"));
status.add(String.valueOf(json_data.getInt("status")));
userha.add(n);
}
sizearray = text_news.size();
if (sizearray <= 0) {
Toast.makeText(getActivity(), "get data error",
Toast.LENGTH_LONG).show();
} else {
}
} catch (JSONException e) {
// toast(9);
}
return userha;
}
private void adddata(ArrayList<News> newsha2) {
adapter = new CustomAdapterAllNews(getActivity(), newsha2, newsha2, res);
list.setAdapter(adapter);
}
#Override
public void onClick(View v) {
}
}
CustomAdapterAllNews.java
public class CustomAdapterAllNews extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Activity activitynews;
private ArrayList datanews;
private static LayoutInflater inflaternews=null;
public Resources resnews;
News tempValuesnews=null;
int i=0;
TableLayout tableLayout1news;
private List<News> worldpopulationlistnews = null;
private ArrayList<News> arraylistnews;
/************* CustomAdapter Constructor *****************/
public CustomAdapterAllNews(Activity a, ArrayList d, List<News> worldpopulationlist, Resources resLocal) {
/********** Take passed values **********/
activitynews = a;
datanews=d;
resnews = resLocal;
this.arraylistnews = new ArrayList<News>();
this.worldpopulationlistnews = worldpopulationlist;
this.arraylistnews.addAll(worldpopulationlist);
/*********** Layout inflator to call external xml layout () **********************/
inflaternews = (LayoutInflater)activitynews.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(datanews.size()<=0)
return 1;
return datanews.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public ImageView image;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
#SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
vi = inflaternews.inflate(R.layout.list_news, null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.textlistnews);
holder.text1=(TextView)vi.findViewById(R.id.text1listnews);
holder.image=(ImageView)vi.findViewById(R.id.imagelistnews);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if(datanews.size()<=0)
{
holder.text.setText("No Data");
holder.text1.setText("نتیجه یافت نشد");
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/"+"image00",null,null));
}
else
{
/***** Get each Model object from Arraylist ********/
tempValuesnews=null;
tempValuesnews = (News) datanews.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValuesnews.getTitle_news());
holder.text1.setText(tempValuesnews.getText_news());
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/image0",null,null));
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
}
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlistnews.clear();
if (charText.length() == 0) {
worldpopulationlistnews.addAll(arraylistnews);
}
else
{
for (News wp : arraylistnews)
{
if (wp.getTitle_news().toLowerCase(Locale.getDefault()).contains(charText)
| wp.getText_news().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlistnews.add(wp);
}
}
}
notifyDataSetChanged();
}
}
When I put this code:
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
on click does not work for me and I need on click in list view.
Don't use v.setOnclicklistener() in adapter, better use in fragment only as below
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
});

List view items changes position when scrolling android?

In my application i used custom list view adapter. In the list view item i added another layout. because in my service one order have any number of order items. For showing the order items i added the order item layout below to custom list view item.it is working fine. but when scroll the list view the data is changed.
adapter class:
public class PreviousDataAdapter extends BaseAdapter {
ArrayList<PreviousOrderData> bpData;
private ArrayList<PreviousOrderData> arraylist;
ArrayList<OrderItemData> opData;
private ArrayList<OrderItemData> arraylist1;
private Activity activity;
private LayoutInflater inflater;
String g_orderid;
DatabaseHandler db;
SharedPreferences m_sharedPreference;
SharedPreferences.Editor m_editor;
ArrayList<String> circless = new ArrayList<String>();
public PreviousDataAdapter(Activity activity, ArrayList<PreviousOrderData> bpData,ArrayList<OrderItemData> opdata) {
// TODO Auto-generated constructor stub
this.activity = activity;
this.bpData = bpData;
this.opData=opdata;//k?
// this.opData=bpData.get()//opdata;
inflater = LayoutInflater.from(activity);
db = new DatabaseHandler(activity);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return bpData.size();
}
#Override
public Object getItem(int location) {
// TODO Auto-generated method stub
return bpData.get(location);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private int lastPosition = -1;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Typeface custom_regular = Typeface.createFromAsset(activity.getAssets(),
"fonts/OpenSans-Regular.ttf");
m_sharedPreference = activity.getSharedPreferences("save_details", activity.MODE_PRIVATE);
m_editor = m_sharedPreference.edit();
//String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
//final View view;
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.previousorders_listitem, null);
viewHolder.date = (TextView) convertView.findViewById(R.id.date);
viewHolder.orderid = (TextView) convertView.findViewById(R.id.orderid);
viewHolder.amount = (TextView) convertView.findViewById(R.id.amount);
viewHolder.status = (TextView) convertView.findViewById(R.id.status);
viewHolder.ordersinfo=(LinearLayout)convertView.findViewById(R.id.previousorders);
viewHolder.date .setTypeface(custom_regular);
viewHolder.orderid.setTypeface(custom_regular);
viewHolder.amount.setTypeface(custom_regular);
viewHolder.status.setTypeface(custom_regular);
viewHolder.ll_individuvalitem = (LinearLayout) convertView.findViewById(R.id.ll_individuvalitem);
//convertView = view;
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.date.setText(bpData.get(position).getDate());
viewHolder.orderid.setText(bpData.get(position).getOrdername());
viewHolder. amount.setText("Rs."+bpData.get(position).getAmount());
viewHolder. status.setText(bpData.get(position).getStatus());
viewHolder.ordersinfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
g_orderid =bpData.get(position).getOrderid();
Log.v("TAG_ORDERIDADAPTER",""+g_orderid);
new GetReorder().execute(WebUrl.RechargeServiceURL+"APP_Reorder");
}
});
//Log.d("size:",opData.size()+"");
if( opData!= null && opData.size() >0){opData.clear();}
opData = bpData.get(position).getOrderItemDataList();//
if(opData.size()>0){
viewHolder.ll_individuvalitem.removeAllViews();
for (int i = 0; i < opData.size(); i++){
// Log.v("TAG Number loop",""+opData.get(i).getNumber());
View itemview = inflater.inflate(R.layout.previousorders_list_single_items, null);
TextView Number = (TextView)itemview.findViewById(R.id.Number);
TextView RechargeAmount = (TextView)itemview.findViewById(R.id.RechargeAmount);
TextView Rechargestatus = (TextView)itemview.findViewById(R.id.Rechargestatus);
Number.setTypeface(custom_regular);
RechargeAmount.setTypeface(custom_regular);
Rechargestatus.setTypeface(custom_regular);
Number.setText(opData.get(i).getNumber());
RechargeAmount.setText("Rs."+opData.get(i).getRechargeAmount());
Rechargestatus.setText(opData.get(i).getRechargestatus());
viewHolder.ll_individuvalitem.addView(itemview);
}
}
return convertView;
}
class ViewHolder {
TextView date, tx_month, orderid, amount,status;
LinearLayout ll_individuvalitem,ordersinfo;
}
private class GetReorder extends AsyncTask<String, Void, JSONObject> {
/*String mJourneyDate;
public GetData(String pJourneyDate) {
this.mJourneyDate = pJourneyDate;
}*/
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = ProgressDialog.show(getActivity(), "", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
nameValuePair.add(new BasicNameValuePair("OrderID", g_orderid));
nameValuePair.add(new BasicNameValuePair("DeviceID", m_sharedPreference.getString("deviceId","")));
nameValuePair.add(new BasicNameValuePair("PlatformID", "3"));
nameValuePair.add(new BasicNameValuePair("UserUniqueID", m_sharedPreference.getString("useruid","")));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
String Status;
super.onPostExecute(result);
// Log.v("TAG_RESULT",""+result);
if (result != null) {
try {
Intent intent= new Intent(activity, Payment_Actiivity.class);
intent.putExtra("jsonfrompayment",result.toString());
Log.v("TAG_JSONPAY",""+result.toString());
activity.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(activity, "something went wrong", Toast.LENGTH_LONG).show();
}
}
}
}
In your adapter class override these two methods
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
Note: For recyclerview just method getItemViewType(int position) will work.
I had the same issue then below link resolved my problem ;
https://stackoverflow.com/a/36738935/3341089
Basically, you should specify your item types then reconfigure your adapter via getItemViewType(int position) and getViewTypeCount() override methods.
If you look into above link, you will get it.
you are using two arrays - "bpData" and "opData" and you only reset if under specific conditions with "opData".
This is a bad design. You need one array - if "opData" is dependent on "bpData" then make it a variable of "bpData".
Or else write something to synchronize the two. Otherwise, you do not know how the display will work.

Scrolldown issue in CustomListView

I am developing android application about CustomListView,firstly I am parsing data from web servis then I add this data to ListView but When I pull down to scrollView I got this error:
at android.widget.ListView.makeAndAddView(ListView.java:1792)
at android.widget.ListView.fillDown(ListView.java:676)
at android.widget.ListView.fillGap(ListView.java:640)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4911)
at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:2923)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3234)
at android.view.View.dispatchTouchEvent(View.java:5553)
MainActivity:
public class MainActivity extends Activity implements OnRefreshListener {
ListView list;
String[] web;
Integer[] imageId = { R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe
};
SwipeRefreshLayout swipeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
web = new String[13];
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
AsyncCallBanner banner = new AsyncCallBanner();
// Call execute
banner.execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this,
"You Clicked at " + web[+position], Toast.LENGTH_SHORT)
.show();
}
});
// TODO Auto-generated catch block
// TODO Auto-generated catch block
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
// ////////// for Parsing data
private class AsyncCallBanner extends AsyncTask<Void, Void, String> {
ProgressDialog dialog;
#Override
protected String doInBackground(Void... params) {
Log.i("TAG", "doInBackground");
Connect();
return null;
}
#Override
protected void onPostExecute(String result) {
Log.i("TAG", "onPostExecute");
// txt1.setText(Icerik);
CustomList adapter = new CustomList(MainActivity.this, web, imageId);
list.setAdapter(adapter);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
Log.i("TAG", "onPreExecute");
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Lütfen bekleyiniz");
dialog.setIndeterminate(true);
dialog.show();
}
}
private void Connect() {
// TODO Auto-generated method stub
JSONObject returndata = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://api.androidhive.info/contacts/");
httppost.setHeader("Content-type", "application/json");
JSONObject jsonparameter = new JSONObject();
try {
// jsonparameter.put("AnketID", "3");
httppost.setEntity(new StringEntity(jsonparameter.toString(),
"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
Log.i("#banner_responseString", "" + responseString);
try {
returndata = new JSONObject(responseString);
JSONArray jsonMainNode = returndata.optJSONArray("contacts");
int lengthJsonArr = jsonMainNode.length();
Log.i("#lengthJson", "" + lengthJsonArr);
int sorusayisi = lengthJsonArr;
for (int i = 0; i < sorusayisi; i++) {
if (i == sorusayisi)
break;
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
try {
web[i] = jsonChildNode.optString("name").toString(); // URL
} catch (Exception e) {
}
}
} catch (JSONException e) {
}
} catch (Exception e) {
}
}
}
Custom Class:
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final String[] web;
private final Integer[] imageId;
public CustomList(Activity context, String[] web, Integer[] imageId) {
super(context, R.layout.list_single, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
please change your getView Function as following and test it and feed me back
#Override
public View getView(int position, View view, ViewGroup parent) {
TextView txtTitle=null;
ImageView imageView=null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view== null) {
view= mInflater.inflate(R.layout.list_single, null);
txtTitle = (TextView) view.findViewById(R.id.txt);
imageView = (ImageView) view.findViewById(R.id.img);
}
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return view;
}

AsyncTask and JSON - Android

I'm passing id form FirstFragment to SecondFragment. I need that I'd to send POST request to web service to retrieve JSON, which I need to create content of SecondFragment. SecondFragment is ListView with custom layout. I'm adding that layout with my custom adapter class (MyAdapter). For JSON I also have AsyncTask class (GetCategoryTas) The problem is that the SecondFragment is created before service give me result back. So content is always blank. How can I fix this.
FirstFragment:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Bundle bundle = new Bundle();
bundle.putString("id", menuList.get(position).getAlias());
categoryPage = new FragmentCategoryPage();
categoryPage.setArguments(bundle);
transaction = manager.beginTransaction();
transaction.replace(R.id.mainContainer, categoryPage, "CategoryPage");
transaction.addToBackStack("CategoryPage");
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();
}
SecondFragment:
public class FragmentCategoryPage extends Fragment implements OnItemClickListener {
private ListView lvCategory;
private List<NameValuePair> pair;
private ArrayList<ItemCategory> itemCatList = new ArrayList<ItemCategory>();
private ItemCategory itemCat;
private MyAdapter myAdapter;
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category, container, false);
context = getActivity();
String id = getArguments().getString("id");
pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("category", id));
new GetCategoryTask().execute();
lvCategory = (ListView) view.findViewById(R.id.lvCategory);
myAdapter = new MyAdapter();
lvCategory.setAdapter(myAdapter);
lvCategory.setOnItemClickListener(this);
return view;
}
// Creating own adapter for categories
class MyAdapter extends BaseAdapter {
#Override
public View getView(final int pos, View convertView, ViewGroup parent) {
View row = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.item_layout_category, parent, false);
} else {
row = convertView;
}
TextView tvCatTitle = (TextView) row.findViewById(R.id.tvCategoryTitle);
TextView tvCatDate = (TextView) row.findViewById(R.id.tvCategoryDate);
ImageView ivCatImage = (ImageView) row.findViewById(R.id.ivCategoryImage);
return row;
}
#Override
public int getCount() { return itemCatList.size(); }
#Override
public Object getItem(int pos) { return null; }
#Override
public long getItemId(int pos) { return 0; }
}
public class GetCategoryTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Variables.URL_CATEGORY);
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String data = EntityUtils.toString(httpEntity);
int status = httpResponse.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jRealObject = jArray.getJSONObject(i);
itemCat = new ItemCategory();
itemCat.setId(jRealObject.get("id").toString());
itemCat.setTitle(jRealObject.get("title").toString());
itemCat.setImage_name(jRealObject.get("image_name").toString());
itemCatList.add(itemCat);
}
return true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == false) {
Toast.makeText(context, Variables.ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
}
}
}
}
How can I fix this problem?
You should refresh your adapter in onPostExecute() by calling;
myAdapter.notifyDataSetChanged();
I dont see anywhere in your code that you have connected your listview with the itemCatList. And you should do anything you wanna do with your listview in onPostExecute, not in onCreate, so you could be sure that the list exists in that point as AsyncTask runs on its own thread
in onPostExecute
lv = (ListView) findViewById(R.id.your_list_view_id);
List<String> your_array_list = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
your_array_list );
lv.setAdapter(arrayAdapter);

Categories

Resources