I am developing an app in which my previous colleague used GridView to show data,but i want to use recyclerview with cardadapter, but I am not getting how to do that.
Here is my code for mainActivity:
public class ActivityCategoryList extends Activity {
GridView listCategory;
ProgressBar prgLoading;
TextView txtAlert;
// declare adapter object to create custom category list
AdapterCategoryList cla;
// create arraylist variables to store data from server
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String CategoryAPI;
int IOConnect = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setTitle("Category");
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listCategory = (GridView) findViewById(R.id.listCategory);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new AdapterCategoryList(ActivityCategoryList.this);
// category API url
CategoryAPI = Constant.CategoryAPI+"?accesskey="+Constant.AccessKey;
// call asynctask class to request data from server
new getDataTask().execute();
// event listener to handle list when clicked
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu page
Intent iMenuList = new Intent(ActivityCategoryList.this, ActivityMenuList.class);
iMenuList.putExtra("category_id", Category_ID.get(position));
iMenuList.putExtra("category_name", Category_name.get(position));
startActivity(iMenuList);
overridePendingTransition(R.anim.open_next, R.anim.close_next);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityCategoryList.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case R.id.refresh:
IOConnect = 0;
listCategory.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// clear arraylist variables before used
void clearData(){
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available show data on list
// otherwise, show alert text
if((Category_ID.size() > 0) && (IOConnect == 0)){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from Category API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject category = object.getJSONObject("Category");
Category_ID.add(Long.parseLong(category.getString("Category_ID")));
Category_name.add(category.getString("Category_name"));
Category_image.add(category.getString("Category_image"));
Log.d("Category name", Category_name.get(i));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//cla.imageLoader.clearCache();
listCategory.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
}
Here is the Code for Adapter Class:
class AdapterCategoryList extends BaseAdapter {
private Activity activity;
public ImageLoader imageLoader;
public AdapterCategoryList(Activity act) {
this.activity = act;
imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return ActivityCategoryList.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_list_item, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.txtText);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);
holder.txtText.setText(ActivityCategoryList.Category_name.get(position));
imageLoader.DisplayImage(Constant.AdminPageURL+ActivityCategoryList.Category_image.get(position), holder.imgThumb);
return convertView;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}
I am new to this, and I think for recyclerview we need to create a list class also.
If anyone have any idea about this, can you help me?
I didn't check your whole code, but the key steps to archieve this is:
set an adapter
recyclerView.setAdapter(adpter);
and create and set an LayoutManager
int columns=3;
reyclerView.setLayoutManager(new GridLayoutManager(context,columns););
see RecyclerView docs and GridLayoutManager
GridView is different and GridLayoutManager is different.So, first you will have to create a recyclerview with the GridLayoutManager.
Remove GridView from respective xml and use Recyclerview with GridLayoutManager
Create Recycler Adapter using the AdapterCategoryList
Related
I make Android application with master/detail pattern. So I have
ListActivity class which is FragmentActivity and
ListFragment class which is Fragment
It all works perfect, but when I change screen orientation it calls again AsyncTask and reload all data.
Here is the code for ListActivity class where I handle all logic:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setTitle("Dnevni horoskop");
if(findViewById(R.id.details_container) != null){
//Tablet
mTwoPane = true;
//Fragment stuff
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
DetailsFragment df = new DetailsFragment();
ft.add(R.id.details_container, df);
ft.commit();
}
pb = (ProgressBar) findViewById(R.id.pb_list);
tvNoConnection = (TextView) findViewById(R.id.tv_no_internet);
ivNoConnection = (ImageView) findViewById(R.id.iv_no_connection);
list = (GridView) findViewById(R.id.gv_list);
if(mTwoPane == true){
list.setNumColumns(1);
//list.setPadding(16,16,16,16);
}
adapter = new CustomListAdapter();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
pos = position;
if(mTwoPane == false){
Bundle bundle = new Bundle();
bundle.putSerializable("zodiac", zodiacFeed);
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
i.putExtra("position", position);
i.putExtras(bundle);
startActivity(i);
overridePendingTransition(R.anim.right_in, R.anim.right_out);
}
else if(mTwoPane == true){
DetailsFragment fragment = (DetailsFragment) getSupportFragmentManager().findFragmentById(R.id.details_container);
fragment.setHoroscopeText(zodiacFeed.getItem(position).getText());
fragment.setLargeImage(zodiacFeed.getItem(position).getLargeImage());
fragment.setSign("Dnevni horoskop - "+zodiacFeed.getItem(position).getName());
fragment.setSignDuration(zodiacFeed.getItem(position).getDuration());
// inflate menu from xml
/*if(menu != null){
MenuItem item = menu.findItem(R.id.share);
Toast.makeText(getApplicationContext(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
}*/
}
}
});
if(!Utils.isConnected(getApplicationContext())){
pb.setVisibility(View.GONE);
tvNoConnection.setVisibility(View.VISIBLE);
ivNoConnection.setVisibility(View.VISIBLE);
}
//Calling AsyncTask to load data
Log.d("TAG", "loading");
HoroscopeAsyncTask task = new HoroscopeAsyncTask(pb);
task.execute();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
public CustomListAdapter() {
layoutInflater = (LayoutInflater) getBaseContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
// Set the total list item count
return names.length;
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
zodiacItem = zodiacList.get(pos);
if (listItem == null && mTwoPane == false) {
listItem = layoutInflater.inflate(R.layout.list_item, null);
}
else if(mTwoPane == true){
listItem = layoutInflater.inflate(R.layout.tablet_list_item, null);
}
// Initialize the views in the layout
ImageView iv = (ImageView) listItem.findViewById(R.id.iv_horoscope);
iv.setScaleType(ScaleType.CENTER_CROP);
TextView tvName = (TextView) listItem.findViewById(R.id.tv_zodiac_name);
TextView tvDuration = (TextView) listItem.findViewById(R.id.tv_duration);
iv.setImageResource(zodiacItem.getImage());
tvName.setText(zodiacItem.getName());
tvDuration.setText(zodiacItem.getDuration());
Animation animation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.push_up);
listItem.startAnimation(animation);
animation = null;
return listItem;
}
}
private void getHoroscope() {
String urlString = "http://balkanandroid.com/download/horoskop/examples/dnevnihoroskop.php";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
runOnUiThread(new Runnable() {
public void run() {
try {
Log.d("TAG", "Response from server : n "
+ response_str);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
} catch (Exception ex) {
Log.e("TAG", "error: " + ex.getMessage(), ex);
}
}
private class HoroscopeAsyncTask extends AsyncTask<String, Void, Void> {
public HoroscopeAsyncTask(ProgressBar pb1){
pb = pb1;
}
#Override
protected void onPreExecute() {
pb.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
getHoroscope();
try {
Log.d("TAG", "test u try");
JSONObject jsonObject = new JSONObject(response_str);
JSONArray jsonArray = jsonObject.getJSONArray("horoscope");
for(int i=0;i<jsonArray.length();i++){
Log.d("TAG", "test u for");
JSONObject horoscopeObj = jsonArray.getJSONObject(i);
String horoscopeSign = horoscopeObj.getString("name_sign");
String horoscopeText = horoscopeObj.getString("txt_hrs");
zodiacItem = new ZodiacItem(horoscopeSign, horoscopeText, duration[i], images[i], largeImages[i]);
zodiacList.add(zodiacItem);
zodiacFeed.addItem(zodiacItem);
//Treba u POJO klasu ubaciti sve.
Log.d("TAG", "ZNAK: "+zodiacItem.getName()+" HOROSKOP: "+zodiacItem.getText());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("TAG", "error: " + e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
pb.setVisibility(View.GONE);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
Here is the code for ListFragment class:
public class ListFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Retain this fragment across configuration changes.
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_list, container, false);
return view;
}
}
I believe part of the problem could be that the orientation change calls onCreate again.
See this question, and check the second answer.
Just adding configChanges to android manifest won't solve the problem, but if you override onConfigurationChanged, you could for example, set a SharedPreferences value were you say "AsynTaskStarted=true" or something like that, so when the orientation changes, you can check this flag and either start the AsyncTask if not present, r just skip that if it's already running.
This other question, referenced by the first answer to the first question linked, seems to have more info.
when orientation changes you can use the following to retain the task:
#Override
public HoroscopeAsyncTask onRetainCustomNonConfigurationInstance() {
return task;
}
then in your onCreate() you can do something like this:
task = (HoroscopeAsyncTask)this.getLastCustomNonConfigurationInstance();
if(task != null) {
//pass the new progressbar reference to the asynctask
//implement a method in the asynctask that returns the task result
//e.g. result = task.getResult();
// if the result is not null, it means the task finished its work while orientation
// changed, if the result is null, onPostExecute will take care of that.
//if(result != null) { //set the result in the listview }
} else {
HoroscopeAsyncTask task = new HoroscopeAsyncTask(pb);
task.execute();
}
the code is trying to get the retained taks, if there isn't one (app started) execute a new asynctask, if there is one (orientation change) use the existing running asynctask.
try this code in manifest m8 android:configChanges="orientation|keyboardHidden"
I have created listview using the following code
public class homeScreen extends Activity{
ArrayList<SingleRow> list;
boolean flag = false;
String space = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
final Context c = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
//putting actual values in array
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
int[] images = {R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i = 0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
final ListView list1 = (ListView)findViewById(R.id.spacelist);
final MySimpleAdapter adapter = new MySimpleAdapter(this,list);
list1.setAdapter(adapter);
space = getIntent().getStringExtra("spaceName");
if(null! = space){
adapter.addView(space);
}
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
if((titles[position]).equalsIgnoreCase("My Ideas")){
Intent i = new Intent(homeScreen.this, privateSpaceList.class);
startActivity(i);
} else if((titles[position]).equalsIgnoreCase("Create New Space")){
Intent i = new Intent(homeScreen.this, createNewSpace.class);
startActivity(i);
}
}
});
}
}
Row class:
class SingleRow{
String title;
int image;
public SingleRow(String title,int image) {
this.title = title;
this.image = image;
}
}
Adapter:
class MySimpleAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
private Context context;
public MySimpleAdapter(Context c,ArrayList<SingleRow> list) {
this.context = c;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void addView(String space) {
int rows = this.getCount();
list.add(rows, new SingleRow(space,R.drawable.ic_launcher));
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewgroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row,viewgroup,false);
TextView title = (TextView)row.findViewById(R.id.label);
ImageView image = (ImageView)row.findViewById(R.id.imageView);
SingleRow temp = list.get(i);
title.setText(temp.title);
image.setImageResource(temp.image);
return row;
}
}
code for create new space
public class createNewSpace extends Activity{
Button add;
TextView sname,pname;
ListView plist;
int success;
Jparser jsonParser = new Jparser();
JSONObject json;
private ProgressDialog pDialog;
ArrayList<String> usersList;
ArrayList<String> spaceUsers;
private static String url_users = "http://10.0.2.2/phpdata/getting_allusers.php";
private static String url_create_space = "http://10.0.2.2/phpdata/create_space.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UNAME = "firstName";
// products JSONArray
JSONArray users = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createnewspace);
sname=(TextView)findViewById(R.id.spaceName);
pname=(TextView)findViewById(R.id.participents);
plist=(ListView)findViewById(R.id.participantlist);
add=(Button)findViewById(R.id.button1);
// Hashmap for ListView
usersList= new ArrayList<String>();
spaceUsers=new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new getAllUsers().execute();
}
});
plist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String users[]=usersList.toArray(new String[usersList.size()]);
Toast.makeText(getApplicationContext(), "User "+users[arg2]+ " added to space "+sname.getText(), Toast.LENGTH_SHORT).show();
spaceUsers.add(users[arg2]);
}
});
// Loading users in Background Thread
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menuspace, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return MenuChoice(item);
}
private boolean MenuChoice(MenuItem item)
{
switch(item.getItemId())
{
case R.id.create:
new createSpace().execute();
return true;
}
return false;
}
class createSpace extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i=0;i<spaceUsers.size();i++)
{
String sname1 = sname.getText().toString();
String uname = spaceUsers.get(i);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sname", sname1));
params.add(new BasicNameValuePair("uname", uname));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_space,
"POST", params);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully inserted user details
Intent is = new Intent(getApplicationContext(), homeScreen.class);
is.putExtra("spaceName", sname1);
startActivity(is);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
class getAllUsers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON Object
json = jsonParser.makeHttpRequest(url_users,"GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// getting value of success tag
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 1) {
// Getting Array of users
try{
JSONArray users=json.getJSONArray(TAG_USERS);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
Log.d("check", "success");
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_UNAME);
Log.d("name....",name);
// adding HashList to ArrayList
usersList.add(name);
}
} catch(JSONException e)
{
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
plist.setAdapter(new ArrayAdapter<String>(createNewSpace.this,android.R.layout.simple_list_item_1,usersList));
}
});
}
}
}
Now I want to add Item to this existing list.
I am taking data from another activity using intent.
Now one item get added.but next time that get replaced.
Please Help.
Thank you in advance.
You should move the creation of the data outside of the adapter:
list=new ArrayList<SingleRow>();
//putting actual values in array
Resources res=c.getResources();
String[] titles=res.getStringArray(R.array.titles);
int[] images={R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i=0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
Pass the list variable to the adapter and store a reference to it there. Then you can just update the data in the list variable, and call notifyDataSetChanged() on your adapter.
Edit: It seems you want to store the space values, and then retrieve them in the HomeScreen activity later. If I understand the flow of your app correctly, then the createNewSpace class should store the space in SharedPreferences. Then in the HomeScreen activity you should retrieve those from the SharedPreferences, and show them.
You can add data to the adapter and call notifyDataSetChanged().Alternatively, You can create a new adapter and listView.setAdapter(adapter) that adapter.
I'm a noob to android development and I'm trying to implement the search bar so that i can search a listview. I have no issues getting the searchview to appear. However, when I enter text into the searchview the app crashes saying that there is an "illegalstateexception: I cannot call onTextChanged with a non filterable adapter. I don't understand why i am getting this error because my adapter class implements Filterable. Any help is greatly appreciated.
Main Activity
public class StoresActivity extends SherlockActivity implements OnQueryTextListener {
ArrayList<HashMap<String, String>> storeList;
ListView list;
LazyAdapter adapter;
EditText inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stores);
storeList = new ArrayList<HashMap<String, String>>();
list=(ListView)findViewById(R.id.list);
SharedPreferences preferences = getSharedPreferences("Oleref", 2);
String employee = preferences.getString("employee", null);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.bigmoney.com="+ employee});
try {
storeList = task.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter=new LazyAdapter(this, storeList);
list.setAdapter(adapter);
list.setItemsCanFocus(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Create the search view
SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
//list = getListView();
list.setTextFilterEnabled(true);
setupSearchView(searchView);
menu.add(0, 1, 1, "Search Text")
.setIcon(R.drawable.ic_launcher)
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return super.onCreateOptionsMenu(menu);
}
private void setupSearchView(SearchView mSearchView) {
mSearchView.setIconifiedByDefault(false);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setOnQueryTextListener(StoresActivity.this);
mSearchView.setQueryHint("Search Text");
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
list.clearTextFilter();
} else {
list.setFilterText(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
Intent chart = new Intent();
chart.setClass(StoresActivity.this, StoresActivity.class);
chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
StoresActivity.this.startActivity(chart);
return true;
case 2:
Intent chart2 = new Intent();
chart2.setClass(StoresActivity.this, WalkInActivity.class);
chart2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
StoresActivity.this.startActivity(chart2);
return true;
}
return true;
}
}
Adapter Class
public class LazyAdapter extends BaseAdapter implements Filterable {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public String sn;
StoresActivity storesActivity;
HashMap<String, String> stores;
HashMap<String, String> storedata;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.store_row, null);
TextView store = (TextView)vi.findViewById(R.id.storeText); // title
TextView store_num = (TextView)vi.findViewById(R.id.store_num); // artist name
TextView street = (TextView)vi.findViewById(R.id.address);
TextView city = (TextView)vi.findViewById(R.id.city);
Button newbutton=(Button)vi.findViewById(R.id.newser);
Button historybutton=(Button)vi.findViewById(R.id.history);
storedata = new HashMap<String, String>();
storedata = data.get(position);
newbutton.setTag(position);
newbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent chart = new Intent();
chart.setClass(v.getContext(), SectionActivity.class);
storedata = data.get((Integer)v.getTag());
sn = storedata.get("Store_Num");
String store = storedata.get("Store");
chart.putExtra("sn", sn);
chart.putExtra("store", store);
chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(chart);
}
});
historybutton.setTag(position);
historybutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent chart = new Intent();
chart.setClass(v.getContext(), HistoryList.class);
storedata = data.get((Integer)v.getTag());
sn = storedata.get("Store_Num");
String store = storedata.get("Store");
chart.putExtra("sn", sn);
chart.putExtra("store", store);
chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(chart);
}
});
// Setting all values in listview
store.setText(storedata.get("Store"));
store_num.setText(storedata.get("Store_Num"));
street.setText(storedata.get("Address"));
city.setText(storedata.get("City") + " " + storedata.get("State") + " " + storedata.get("Zip"));
return vi;
}
public boolean onLoadClass(Class arg0) {
// TODO Auto-generated method stub
return false;
}
//Added for search BJR 5-16-2013
#Override
public android.widget.Filter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
Since you are using ActionBarSherlock, I assume that your min SDK is below 11 but SearchView widget requires Android 3.0 (API Level 11) and higher. You might want to look at search dialog. Please check documentation http://developer.android.com/guide/topics/search/search-dialog.html
Hi i am very new to this android..Actually i am trying to display 1 heading and description below it in a screen.I have done that using Galleryview.I don't know whether this is correct way to do this r not..
My actually idea is..In galleryview if i swipe the screen the next(heading and description should come) but i can't do this..SO i tried to keep next and previous option to do this..But this also i cant do ..I know that i am doing in wrong way.Please suggest me some goodway to do this.. I am ready to give more explanation if needed..The code below posted is what i done..
My Activity code:
public class NewsDescription extends Activity
{
// private String url = "http://m.indiatoday.in/xml/stories/"+(String)context.getInstance().getAppVariable("storyurl");
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.newsdesgallery);
Gallery gl=(Gallery)findViewById(R.id.GalleryNewsDesc);
NewsDescriptionAdapter adapter =new NewsDescriptionAdapter(this);
gl.setAdapter(adapter);
}
}
My adapter class:
public class NewsDescriptionAdapter extends BaseAdapter
{
private static Context contxt;
String[] body= {};//new String[30];
String[] heading= {};//new String[30];
NewsDescriptionAdapter(Context conxt)
{
// System.out.println("inside cons");
this.contxt=conxt;
getelement();
}
public void getelement()
{
// System.out.println("Inside getElement");
String[] url=context.getInstance().getselectedUrl();
// System.out.println("After url");
// System.out.println("count="+(String)context.getInstance().getAppVariable("count"));
int count = Integer.parseInt((String)context.getInstance().getAppVariable("count"));
// System.out.println("count="+count);
// System.out.println("after count="+url[count]);
String URL = "http://xxxx.in/xml/stories/"+url[count];
// System.out.println("url="+URL);
TaplistingParser parser = new TaplistingParser();
// try {
// url=URLEncoder.encode(url, "UTF-8");
// } catch (UnsupportedEncodingException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
URL=URL.replace(" ","");
// System.out.println("url="+url);
String xml= parser.getXmlFromUrl(URL);
Document doc=parser.getDomElement(xml);
NodeList n1 = doc.getElementsByTagName("item");
body = new String[n1.getLength()];
heading = new String[n1.getLength()];
for( int i = 0 ; i < n1.getLength(); i++ )
{
// HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) n1.item(i);
body[i]=parser.getValue(e, "body");
heading[i]=parser.getValue(e, "headline");
// map.put("Body", parser.getValue(e,"body"));
// menuItems.add(map);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return body.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return body[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
// System.out.println("body="+body[position]);
if (convertView == null)
{
//this should only ever run if you do not get a view back
LayoutInflater inflater = (LayoutInflater) contxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newsdescriptionrow, null);
}
TextView next =(TextView)convertView.findViewById(R.id.nextnews);
// final Gallery gal=(Gallery)convertView.findViewById(R.id.GalleryNewsDesc);
next.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
System.out.println("Inside next");
int count = Integer.parseInt((String)context.getInstance().getAppVariable("count"));
count++;
context.getInstance().setAppVariable("count", Integer.toString(count));
}
});
TextView textViewhead = (TextView) convertView
.findViewById(R.id.name_DescHeading);
textViewhead.setText(heading[position]);
TextView textView = (TextView) convertView
.findViewById(R.id.name_Desclabel);
textView.setText(body[position]);
return convertView;
}
}
You should not use gallery widget any more as it is deprecated in newer version of android. Instead you can use a ViewPager from android support jar.
You can find an example in here :
https://github.com/nostra13/Android-Universal-Image-Loader
Lookout for ImagePagerActivity in the above code. You can create a custom cell with an imageview and textview for description (modify the item_pager_image xml). Let me know how it goes.
*
*
My Problem is that each Activity in my App gets data from Web Service and if
it remains idle for some OS dialog pops up showing Force Close and OK
option. when i clicks force close it stops but when i click Ok button it remains
in Activity, but when i move to other activity no data is shown as it does not hit web service
to get data for that activity
So, how to handle this situation
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.coupon_layout);
context = this;
merchantName = (TextView) findViewById(R.id.CouponsMerchantName);
address = (TextView) findViewById(R.id.CouponsDetailAddress);
phone = (TextView) findViewById(R.id.CouponsDetailsPhone);
categoryImage = (ImageView) findViewById(R.id.CouponsCategoryImage01);
couponsListLayout = (ListView) findViewById(R.id.CouponsListLayout);
backButton = (Button) findViewById(R.id.CouponsBackButton);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
try {
entry = Data.storeMecrchantDetailMain.get(0);
merchantName.setText(entry.getMerchantName());
address.setText(entry.getAddress());
phone.setText(entry.getPhone());
ImageLoader imageLoader = new ImageLoader(CouponsActivity.this);
String categoryImg = Data.URL_BASE + entry.getCategoryImg();
categoryImage.setTag(categoryImg);
imageLoader.DisplayImage(categoryImg, CouponsActivity.this,
categoryImage);
adapter = new CustomAdapterCoupons(this, entry.getCouponsList());
couponsListLayout.setAdapter(adapter);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class CustomAdapterCoupons extends BaseAdapter {
/* Variable Declaration */
private Context context;
private List<CouponBean> list;
private CouponBean entry;
public com.a.util.ImageLoader imageLoader;
private LayoutInflater inflater;
public CustomAdapterCoupons(Context context, List<CouponBean> list) {
this.context = context;
this.list = list;
inflater = (LayoutInflater) CouponsActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new com.abc.util.ImageLoader(context);
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class ViewHolder {
public TextView couponName, couponCode, usageDescription,
expirationDate;
public ImageView couponImage;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
entry = list.get(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.coupons_list_layout,
null);
holder = new ViewHolder();
holder.couponName = (TextView) convertView
.findViewById(R.id.CouponListCouponName);
holder.couponCode = (TextView) convertView
.findViewById(R.id.CouponListCouponCode);
holder.expirationDate = (TextView) convertView
.findViewById(R.id.CouponListDetailDate);
holder.usageDescription = (TextView) convertView
.findViewById(R.id.CouponListUsageDescription);
holder.couponImage = (ImageView) convertView
.findViewById(R.id.CouponListLeftImage);
convertView.setTag(holder);
// Set the display text
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.couponName.setText(entry.getCouponName());
holder.expirationDate.setText(context
.getString(R.string.Coupon_Expiration_Date)
+ "\n"
+ entry.getExpirationDate());
holder.usageDescription.setText(entry.getUsageDescription());
holder.couponCode.setText(entry.getCouponCode());
holder.couponImage.setTag(Data.URL_BASE_2 + entry.getCouponImage());
imageLoader.DisplayImage(Data.URL_BASE_2 + entry.getCouponImage(),
(Activity) context, holder.couponImage);
Log.v(Data.LOG3, "image" + entry.getCouponImage());
final Button savedMyCoupons = (Button) convertView
.findViewById(R.id.CouponListAddtoMyCouponButton);
if (entry.getSavedMyCoupons().equalsIgnoreCase("N")) {
savedMyCoupons.setText(context
.getString(R.string.Add_to_myCoupons));
savedMyCoupons.setBackgroundResource(R.drawable.done_btn);
savedMyCoupons.setTag(entry.getCouponId().toString());
savedMyCoupons.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
createProgressDialog();
new Loader()
.execute(savedMyCoupons.getTag().toString());
}
});
} else if (entry.getSavedMyCoupons().equalsIgnoreCase("Y")) {
savedMyCoupons.setText(context
.getString(R.string.Already_Added_to_my_coupons));
savedMyCoupons.setBackgroundColor(Color.WHITE);
savedMyCoupons.setTextColor(Color.BLACK);
}
// display the view corresponding to data at specified position
return convertView;
}
}
private void createProgressDialog() {
progressDialog = new ProgressDialog(context);
// progressDialog.setIcon(R.drawable.icon);
progressDialog.setTitle(R.string.Please_Wait);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setIndeterminateDrawable(context.getResources()
.getDrawable(R.anim.simple_animation));
progressDialog.setMessage(context.getString(R.string.Please_Wait));
progressDialog.show();
}
#Override
public void onResume() {
Log.v(Data.LOG, "On Resume");
super.onResume();
}
class Loader extends AsyncTask<String, String, String> {
Boolean value;
protected String doInBackground(String... arg0) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Data.URL_POST_DATA);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("couponsubmit",
"submit"));
nameValuePairs.add(new BasicNameValuePair("sid",
Data.GET_SESSION_ID));
nameValuePairs.add(new BasicNameValuePair("api", "on"));
nameValuePairs.add(new BasicNameValuePair("couponid",
arg0[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// String result = responseBody;
Log.v(Data.LOG1, "Response : " + responseBody);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (Exception e) {
Log.e(Data.LOG, "" + e.getMessage());
e.printStackTrace();
}
LocateServices.getInstance().getStoreMerchantDetails(
entry.getMerchantID());
return null;
}
#Override
protected void onPostExecute(String result) {
// TODOAuto-generated method stub
super.onPostExecute(result);
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
entry = Data.storeMecrchantDetailMain.get(0);
adapter = new CustomAdapterCoupons(context,
entry.getCouponsList());
couponsListLayout.setAdapter(adapter);
progressDialog.dismiss();
}
};
}
}
Thanks for any help.
*
The dialog you are talking about is called ANR(Activity Not Responding) dialog, and there's no any method by which you can get the dialog to go away, and you should not try to remove it either.
You can however, call a new thread and run the methods to get data from web in that separate thread, instead of the UI thread.
Another method could be to start the fetching method after a second. The code example for this could be like this:
new Handler().postDelayed(new Runnable() {
public void run() {
//Your method to get data from web here
}
}, 1000); //delay in milliseconds
The above code will delay the fetching method by a second, so that the ANR dialog can be tricked away. However you should use a separate thread instead of this for better result.
Do your fetching in the background, your users will be happy. I use AsyncTask.
Try using Async Task function
Declare the function using
new AsynBackground().execute(u);
and implement the function as follows
private class AsynBackground extends AsyncTask<String, Void, Void>
{
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
fetchDistancesFromGoogle(params[0]);
return null;
}
}