load a few json elements at a time by scrollview - android

I have a ListFragment that contains a list of items. I would like to load say 9 items at a time and when i scroll and reach the bottom of the listview i want to load another 9 items in background.
I make 2 request to my web server:
1) to get all the item id's of the items, by a searh() method
2) to get all the item details of a specific item though its id, by getId(id) method
The version i have implemented gets all the ids and then loads all the items at once in the doInBackground method of AsyncTask and it works. and it takes very long (i dont want a button because its really ugly).
I'd like to introduce this thing about the onScrollListener so that when i first open my app, in background i get all the ids, and then i get the first 9 items and show them. then when i scroll to the end i want to load the next 9 items. How do i do this?
I have read a few posts but it not clear to me, especially due to the fact that i have 2 functions that need to be run in background, 1 function needs to be run once while the other many times and i need to keep track of which id's i getting.
I would also if possible like to add the function that if i pull the ListView a little then it should update my view.
Here is my code:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.adapter.ListViewAdapter;
import com.prjma.lovertech.util.MVPFunctions;
public class CompraFragment extends ListFragment {
public ListView listView;
public ListViewAdapter adapter;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private DownloadTask mDownloadTask = null;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_compra, false);
View rootView = inflater.inflate(R.layout.fragment_compra, container, false);
// now you must initialize your list view
listView = (ListView) rootView.findViewById(android.R.id.list);
mDownloadTask = new DownloadTask();
mDownloadTask.execute((Void) null);
return rootView;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog progressDialog;
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
//Here i get all the id's
ArrayList<Long> ids = MVPFunctions.getMioSingolo().search();
//for each id get all its details and put it in a map
items = new ArrayList<HashMap<String, Object>>();
for(int i=0; i < ids.size(); i++){
items.add(MVPFunctions.getMioSingolo().getItem(ids.get(i)));
}
return true;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(getActivity(), "", "Downloading Content...");
}
#Override
protected void onPostExecute(final Boolean success) {
mDownloadTask = null;
// dismiss the dialog after getting all products
progressDialog.dismiss();
//showProgress(false);
if (items.get(0).get("status error")!= null){
Toast.makeText(getActivity(), "status error = " + items.get(0).get("status error"), Toast.LENGTH_LONG).show();
Log.i("status error put toast", (String) items.get(0).get("status error"));
//fai qualcosa, tipo torna indietro, ecc
}
// updating UI from Background Thread
ListViewAdapter adapter = new ListViewAdapter(getActivity(),R.layout.listview_item_row, items, icon);
// updating listview
listView.setAdapter(adapter);
}
#Override
protected void onCancelled() {
mDownloadTask = null;
//showProgress(false);
}
}
}
Adapter class:
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.activity.DettagliActivity;
import com.prjma.lovertech.model.Item;
public class ListViewAdapter extends ArrayAdapter<String> {
private static LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
//public ImageLoader imageLoader;
public ListViewAdapter(Context context, int listviewItemRow, ArrayList<HashMap<String, Object>> items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder viewHolder = new ViewHolder();
if (row == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.listview_item_row, null);
viewHolder.ic_thumbnail = (ImageView)row.findViewById(R.id.ic_thumbnail);
viewHolder.scadenza = (TextView)row.findViewById(R.id.tvScadenza);
viewHolder.prezzo = (TextView)row.findViewById(R.id.tvPrezzo);
viewHolder.followers = (TextView)row.findViewById(R.id.tvFollowers);
viewHolder.hProgressBar = (ProgressBar)row.findViewById(R.id.hProgressBar);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)row.getTag();
}
HashMap<String, Object> item = items.get(position);
viewHolder.ic_thumbnail.setImageBitmap((Bitmap) item.get("pic1m"));
viewHolder.scadenza.setText((CharSequence) item.get("scadenza"));
viewHolder.prezzo.setText((CharSequence) item.get("prezzo"));
viewHolder.followers.setText((CharSequence) item.get("followers"));
viewHolder.hProgressBar.setProgress((Integer) item.get("coefficient"));
//row.onListItemClick(new OnItemClickListener1());
row.setOnClickListener(new OnItemClickListener(position));
return row;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
static class ViewHolder {
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
}
}

In your adapter, check how close the user is from the bottom of the data set. When they get to the end, call a method that fetches more items from the network. I normally use a "REFRESH_THRESHOLD" integer to prefetch items before they're needed.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Item current = getItem(position);
//Pre-fetch
if(getCount() - position <= REFRESH_THRESHOLD){
//If there are more items to fetch, and a network request isn't already underway
if(is_loading == false && has_remaining_items == true){
getItemsFromNetwork();
}
}

Related

Dynamically adding data to listView which does not overwrite the previous data and permanently saving it

In the following program, When I click on Add button in the options menu a dialog is opened wherein the user enters the data which is then shown in the ListView.
There are a number of problems with his code.
1) age.setText in the Custom Adapter causes the app to crash.Commenting out the age.settext line, it works well for the other two TextViews.
2) When i add data in the list using the dialog the second time, the list gets overwritten and no updation is done.
I want the list to be automatically updated when new data is entered rather than over writing it.
3) The data vanishes away when i restart the app. I want the data to be saved permanently.
Code for Custom Adapter is:
package com.example.sakshi.dialogsandmenus;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<Data> list;
private LayoutInflater mLayoutInflator;
public CustomAdapter(Context context, ArrayList list){
this.context=context;
this.list=list;
mLayoutInflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
dob.setText(list.get(position).getDate());
return convertView;
}
}
Code for Main Activity is:
package com.example.sakshi.dialogsandmenus;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import static android.R.id.list;
import static com.example.sakshi.dialogsandmenus.R.id.date;
public class MainActivity extends AppCompatActivity{
ListView listview;
ArrayList<Data> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView)findViewById(R.id.list_item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
if(id==R.id.add){
filldialog();
}
return super.onOptionsItemSelected(item);
}
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
arrayList = new ArrayList<>();
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
//customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
}
}
1) you have to convert the value of age to String before setText
//age.setText(list.get(position).getAge());
age.setText(Integer.toString(list.get(position).getAge()));
2) Every time new Arraylist initilaization
intarrayList = new ArrayList<>();
ArrayList arrayList = new ArrayList<>();
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
enter code here
3) Use Sqlite or anyStorage Option for data saving
You are setting int value directly to setText of ageTextView. You need to convert int to String before you setting a text to TextView.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
age.setText(String.valueOf(list.get(position).getAge())); // use this it will work
dob.setText(list.get(position).getDate());
return convertView;
}
}
Move these lines outside the onClickListener
arrayList = new ArrayList<>();
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
Because whenever you are clicking the button arraylist is initializing again.

How to extract all the editText's data from a ListView when one single button (save) is pressed

This is the first question I am posting. Here is my question and below given is the debugged code from android studio.
Here, I have tried to extract the data by taking the data from the adapter into the mainActvity, but I failed as the app is crashing on Clicking the save button. Here the data is nothing but and object.
MainActivity :
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<ListItem_Elements> testsList;
int n=5;//No. of tests
Button btn_save;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
btn_save= (Button)findViewById(R.id.btn_save);
//CustomAdapter adapter;
Resources res=getResources();//Takes the resource permission required to show ListView
testsList= new ArrayList<ListItem_Elements>();
testsList = SetList();
adapter= new CustomAdapter(this, testsList, res);
listView.setAdapter(adapter);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(testsList!=null)
saveValues();
}
});
}
public ArrayList<ListItem_Elements> SetList() {
/*Enter the Test names*/
ArrayList<ListItem_Elements>tests_Array= new ArrayList<ListItem_Elements>();
for(int i=0;i<5;i++) {
ListItem_Elements e = new ListItem_Elements();
e.setTest("XYZ");
e.setResult(null);
tests_Array.add(e);
}
return tests_Array;
}
ArrayList<ListItem_Elements>ar= new ArrayList<>();
public void saveValues() {
if(adapter.extractedArray!=null) {
ar = adapter.extractedArray;
Toast.makeText(MainActivity.this, ar.size(), Toast.LENGTH_SHORT).show();
}
}
}
--------------------------------------------------------------------------------
CustomAdapter :
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Activity activity;
public static ArrayList<ListItem_Elements> extractedArray= new ArrayList<ListItem_Elements>();
private ArrayList<ListItem_Elements> array;
//Declaration of ArrayList which will be used to recieve the ArrayList that has to be putup into the ListView
private LayoutInflater inflater; //To Instantiates a layout XML file into its corresponding View
Resources res;
//protected String bridgeValue;
CustomAdapter(Activity a, ArrayList<ListItem_Elements> b, Resources resLocal) {
activity = a;
array= b;
res = resLocal;
//Initialization of inflater to link the layout of list items
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CustomAdapter() {
}
#Override
public int getCount() {
return array.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
// keeping references for views we use view holder
public static class ViewHolder {
/*Declaration of elements of layout of list items in the class for future use of putting up
data onto the List View*/
TextView textView;
EditText editText;
}
#Override
//Here views were bound to a position
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
// if a view is null(which is for the first item) then create view
if (convertView == null) {
vi = inflater.inflate(R.layout.layout_items, null);
// Taking XML files that define the layout of items, and converting them into View objects.
holder = new ViewHolder();//Stores the elements of the layout of list items
/*Initializing the elements of the layout of list item*/
holder.textView = (TextView) vi.findViewById(R.id.textView);
holder.editText = (EditText) vi.findViewById(R.id.editText);
vi.setTag(holder);
//Stores the view(layout of list item) into vi
}
//else if it already exists, reuse it(for all the next items). Inflate is costly process.
else {
holder = (ViewHolder) vi.getTag();
//Restores the already exisiting view in the 'vi'
}
/*Setting the arrayList data onto the different elements of the layout of list item*/
try {
holder.textView.setText(array.get(position).getTest());
if(holder.editText.getText()!=null) {
ListItem_Elements obj = new ListItem_Elements();
obj.setTest(array.get(position).getTest());
obj.setResult(holder.editText.getText().toString());
extractedArray.add(position, obj);
}
}
catch (Exception e) {
e.getMessage();
}
return vi;//Returns the view stored in vi i.e contents of layout of list items
}
}
--------------------------------------------------------------------------------
public class ListItem_Elements {
String test;
String result;
ListItem_Elements() {
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
You are missing some necessary code. EditText has a method called addTextChangedListener() which accepts a TextWatcher implementation. This implementation would be responsible for updating the data in the adapter.
final ListItem_Elements item = array.get(position);
holder.textView.setText(item.getTest());
holder.editText.setText(item.getResult());
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
item.setResult(s.toString());
}
// omitted empty impls for beforeTextChanged() and afterTextChanged(), you need to add them
});
Now, everytime the user updates the EditText, your adapter value will be updated. Then you just get the array values:
public void saveValues() {
// testLists in the activity and array in the adapter are references
// to the same list. So testLists already has the updated results
}
And take out this whole block of code:
holder.textView.setText(array.get(position).getTest());
if(holder.editText.getText()!=null) {
ListItem_Elements obj = new ListItem_Elements();
obj.setTest(array.get(position).getTest());
obj.setResult(holder.editText.getText().toString());
extractedArray.add(position, obj);
}
It doesn't do the right thing.
you are filling the listView with value from an ArrayList. Why you don't just get values from the your ArrayList ??
public void saveValues() {
if(tests_Array!=null) {
//and here you get values from your list
//by a simple for instruction
Toast.makeText(MainActivity.this, tests_Array.size(), Toast.LENGTH_SHORT).show();
}
}

How to fetch datas using json from database and populate it in horizontal listview in android

main xml containing horizontallistview
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
>
<com.example.newomolistview.HorizontalScrollView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ddd"
/>
</LinearLayout>
contain three textviews-for product name,original rate and offer rate
app_custom_list.xml
I think in this java class i have gone wrong
ApplicationAdapter.java
package com.example.newomolistview;
import java.text.NumberFormat;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.newomolistview.R;
import com.example.newomolistview.HorizontalScrollView;
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
// private BaseAdapter mAdapter = new BaseAdapter() {
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_custom_list, null); //new code
// LayoutInflater li = LayoutInflater.from(getContext()); //original
// v = li.inflate(R.layout.app_custom_list, null); //original
// LayoutInflater li = (LayoutInflater) this._context
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// convertView = li.inflate(R.layout.app_custom_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView productName = (TextView)v.findViewById(R.id.textView1);
TextView originalRate = (TextView)v.findViewById(R.id.textView2);
TextView offerRate = (TextView)v.findViewById(R.id.textView3);
if(productName != null) productName.setText(app.getProductName());
if(originalRate != null) originalRate.setText(app.getOriginalRate());
if(offerRate != null) offerRate.setText(app.getOfferRate());
}
return v;
// View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem, null);
// TextView title = (TextView) retval.findViewById(R.id.title);
// title.setText(dataObjects[position]);
//
// return retval;
}
// };
}
I need to populate horizontal listview with json data from database(product name, original rate and offer rate).I used array adapter to populate the horizontal listview. I think I have gone wrong somewhere in ApplicationAdapter.java and MainActivity.java
in this section also, i have gone wrong
MainActivity.java
package com.example.newomolistview;
import java.util.List;
import com.example.newomolistview.HorizontalScrollView;
import com.example.newomolistview.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity implements FetchDataListener{
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// HorizontalScrollView listview = (HorizontalScrollView) findViewById(R.id.listview);
// listview.setAdapter(mAdapter);
initView();
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String key="saasvaap123";
String cityid="1";
String url = "http://www.gooffers.in/omowebservices/index.php/webservice/Public_User/homePagepoffers?";
FetchDataTask task = new FetchDataTask(this);
task.execute(url,key,cityid);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
HorizontalScrollView listview = (HorizontalScrollView) findViewById(R.id.listview); //new code
// create new adapter
ApplicationAdapter mAdapter = new ApplicationAdapter(this, data);
listview.setAdapter(mAdapter); //new code
// set the adapter to list
// setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
I need to populate horizontal listview with json data from database(product name, original rate and offer rate).I used array adapter to populate the horizontal listview. I think I have gone wrong somewhere in ApplicationAdapter.java and MainActivity.java
You can learn it from these tutorials :-
Populating a ListView from JSON
Loading Text in listview from http json data

How to refresh Android GridView?

I am writing a code in Android to refresh a Gridview in every 2 mins. I searched a lot in the web but i don't find any specific technique to do it.
Java Code
MainActivity.java
package com.example.mycustomgridrefresh;
import java.util.ArrayList;
import android.os.Bundle;
import android.widget.GridView;
import android.app.Activity;
public class MainActivity extends Activity
{
GridView gd;
MyGrid mg;
ArrayList<String> abc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gd = (GridView)findViewById(R.id.gd);
abc = new ArrayList<String>();
for(int i=0;i<100;i++)
{
abc.add(String.valueOf(i));
}
mg = new MyGrid(this,this,abc);
gd.setAdapter(mg);
}}
MyGrid.java
package com.example.mycustomgridrefresh;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyGrid extends BaseAdapter
{
ArrayList<String> abc;
Activity activity;
public MyGrid(Activity activity , Context cont,ArrayList<String> abc)
{
super();
this.abc = abc;
this.activity = activity;
}
#Override
public int getCount()
{
return abc.size();
}
#Override
public Object getItem(int arg0)
{
return abc.get(arg0);
}
#Override
public long getItemId(int arg0)
{
return 0;
}
public class ViewHolder
{
public TextView txt;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2)
{
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(arg1==null)
{
view = new ViewHolder();
arg1 = inflator.inflate(R.layout.mygrid, null);
view.txt = (TextView) arg1.findViewById(R.id.txt);
arg1.setTag(view);
}
else
{
view = (ViewHolder) arg1.getTag();
}
view.txt.setText(abc.get(arg0));
return arg1;
}
}
This above Grid is printing 100 numbers is 10 rows & columns. I want to change the value of the grid cells for each 2mins. The value should to change to +1.
Please suggest me some good solution.
Thanks in Advance !!!
To refresh the values you need to call in MyGrid:
notifyDataSetChanged()
To do any task each 2 mins you need to create other thread, something like this:
public void startRunnable(){
Runnable r = new Runnable() {
#Override
public void run() {
while(needToRefresh){
//add one...
this.notifyDataSetChanged();
Thread.sleep(2000);
}
}
};
this.activity.runOnUiThread(r);
}
Don't forget to stop the needToRefresh condition onPause, onStop.
EDIT: Because notifyDataSetChanged() need to be call in UI thread, you need to call runnable using this.activity.runOnUiThread
See there: How to use notifyDataSetChanged() in thread

How to add data from db.selectAll Please check it agian

Now i try to use adapter . But i dont understand how to set value from data .Becuase in friends = db.selectall ,value in friend have 3 value(fname,lname,nickname).So my question is How to set value(fname/lname/nickname OR one or the other) My code NOW look like this ::::
package com.example.sqlite;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sqlite.db.FriendsDB;
import com.example.sqlite.entry.FriendEntry;
public class FriendsListActivity extends Activity {
private Context context;
private FriendsDB db;
private ArrayList<FriendEntry> friends;
private ArrayList<String> data;
private TextView hellotext;
private ListView hellolistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.friendlist_layout);
}
public void showAllList(){
//view matching
hellotext = (TextView) findViewById(R.id.hellotext);
hellolistview = (ListView) findViewById(R.id.hellolistview);
//select data
friends = db.selectAll();
if(friends.size()==0){
Toast.makeText(context,"You dont have any friend.",Toast.LENGTH_SHORT).show();
}else{
data = new ArrayList<String>();
for (int i = 1;i<=friends.size();i++){
// set value for data
**data.add("Your Name is "+friends["fname"]);<< I want to add data like this .How to correct**
}
}
}
private class adapter extends BaseAdapter{
private Holder holder;
#Override
//ดาต้ามีกี่แถว
public int getCount() {
// TODO Auto-generated method stub
return friends.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
//create
if( view == null){
view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_layout,null);
holder = new Holder();
holder.title = (TextView) view.findViewById(R.id.item_title);
view.setTag(holder);
}else{
holder = (Holder) view.getTag();
}
//assign data / wait for data
return null;
}
private class Holder{
//view แต่ละตัวเก็บค่าอะไรบ้าง
public TextView title;
}
}
}
When you have data in Cursor and you want to display it in a ListView, you need to use a CursorAdapter.
You can either use the pre-defined SimpleCursorAdapter or if you want custom views, you can extend the CursorAdapter class.
Tutorial here: http://thinkandroid.wordpress.com/2010/01/11/custom-cursoradapters/
You are doing it allmost all right , but I suggest you to use an ArrayList of HashMap type instead of using Friends class.
This will lower your application burden.
ArrayList<HashMap<Object,String>> list=new ArrayList<HashMap<Object,String>>();
HashMap<Object,String> hm;
in your select all method
do{
hm=new HashMap<Object,String>();
hm.add(Key_Name,"retrieve the value from cursor here");
list.add(hm);
}while(c.movetonect());
return list;
in your activity
ArrayList<HashMap<Object,String>> list=new ArrayList<HashMap<Object,String>>();
list=db.selectAll();
HashMap<Object,String> hm;
for (int i=0;i<list.length;i++){
hm=list.getIndex(i); //retrieve all the vaalues here
}
use list adapters which accept list to populate the listview

Categories

Resources