Parse Query Get Data To List - java

I have a list parameter List list that I am trying to pass the sList back to. How do I get the data to the super class?
Error message says Unable to resolve this.addGroups. I've tried creating a sub list of groups and assigning it, and I have tried directly assigning with List.add
UPDATED FULL CLASS
public class GroupActivity extends ActionBarActivity {
Context context;
RecyclerView groupRecyclerView;
GroupAdapter groupAdapter;
private Toolbar toolbar;
public List<Group> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("POLICE APP");
context = this;
Helpers.setTabs(context, this, 2);
groupRecyclerView = (RecyclerView) findViewById(R.id.ui_Groups_RecyclerView);
this.GetData();
groupAdapter = new GroupAdapter(this, list);
groupRecyclerView.setAdapter(groupAdapter);
groupRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
public void addGroups(List<Group> grps) {
this.list = grps;
}
#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_group, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void GetData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Group");
query.findInBackground(new FindCallback<ParseObject>() {
List<Group> sList;
public void done(List<ParseObject> groupList, ParseException e) {
if (e == null) {
for (int i = 0; i < groupList.size(); i++) {
try {
Group grp1 = new Group("1", groupList.get(i).getString("Name"), " Turn in your time sheets", "d");
sList.add(grp1);
Log.d("group1:", "inserted the group");
} catch (Exception c) {
c.printStackTrace();
Log.d("group1:", c.getMessage().toString());
}
}
this.addGroups.add(sList);
Log.d("groups1", "Retrieved " + groupList.size() + " groups");
} else {
Log.d("groups1", "Error: " + e.getMessage());
}
}
});
}
}

All subclasses can access all fields and methods from super class if they are not private. So, in your case, you have two options:
setList(clist); // I suppose list is private and in super class you made a setter for it
// or
this.list=cList; // if list isn't private
EDIT
How I would make super class:
public class SuperClass{
private List<Group> list;
// class's methods
public void setList(ArrayList<Group> list){
this.list = list;
}
}
EDIT No2
Inspired by your edited question ( :) ), I changed a bit your code and it should work. Test it and post results.
public class GroupActivity extends ActionBarActivity {
Context context;
RecyclerView groupRecyclerView;
GroupAdapter groupAdapter;
private Toolbar toolbar;
public List<Group> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("POLICE APP");
context = this;
Helpers.setTabs(context, this, 2);
groupRecyclerView = (RecyclerView) findViewById(R.id.ui_Groups_RecyclerView);
this.GetData();
groupAdapter = new GroupAdapter(this, list);
groupRecyclerView.setAdapter(groupAdapter);
groupRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
public void addGroups(List<Group> grps) {
this.list = grps;
}
#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_group, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void GetData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Group");
query.findInBackground(new FindCallback<ParseObject>() {
List<Group> sList = new ArrayList<Group>();
public void done(List<ParseObject> groupList, ParseException e) {
if (e == null) {
for (int i = 0; i < groupList.size(); i++) {
try {
Group grp1 = new Group("1", groupList.get(i).getString("Name"), " Turn in your time sheets", "d");
sList.add(grp1);
Log.d("group1:", "inserted the group");
} catch (Exception c) {
c.printStackTrace();
Log.d("group1:", c.getMessage().toString());
}
}
addGroups(sList);
Log.d("groups1", "Retrieved " + groupList.size() + " groups");
} else {
Log.d("groups1", "Error: " + e.getMessage());
}
}
});
}
}
You made some obvious coding mistakes, so that was the problem if I'm right. Try it.

I found the issue. I needed to add this code after the for loop.
groupAdapter = new GroupAdapter(context, list);
groupRecyclerView.setAdapter(groupAdapter);
Basically, Parse was returning async and the view didnt have the new content. Just update the view after your for loop

Related

implementing search-view at the action-bar of the main activity not working probably

I have faced a problem when implementing searchview at the actionbar of the main activity .. where the main activity has bottom navigation menu with three fragments...
and the search view should work at each fragment ...
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private Boolean LoadContact = false ;
private BottomNavigationView navigationView ;
private String SearchText;
int page;
AllContactFrag allContactFrag = new AllContactFrag();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Special Contact");
navigationView =(BottomNavigationView) findViewById(R.id.navigationView);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame, new SpecialContactFrag());
ft.commit();
// navigationView.setSelectedItemId();
navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id)
{
case R.id.action_MyNotes:
Bundle bundle = new Bundle();
bundle.putString("text",SearchText);
Fragment AllNotes = new NotesFrag();
AllNotes.setArguments(bundle);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frame,AllNotes);
transaction.addToBackStack(null);
transaction.commit();
toolbar.setTitle("My Note");
return true;
case R.id.action_AllContact:
Bundle bundle2 = new Bundle();
bundle2.putString("text",SearchText);
Fragment AlxlContact = new AllContactFrag();
AlxlContact.setArguments(bundle2);
FragmentManager xmanager = getSupportFragmentManager();
FragmentTransaction xtransaction = xmanager.beginTransaction();
xtransaction.replace(R.id.frame,AlxlContact);
xtransaction.addToBackStack(null);
xtransaction.commit();
toolbar.setTitle("Phone Contact");
return true;
case R.id.action_Spec:
Fragment AlxxlContact = new SpecialContactFrag();
FragmentManager xxmanager = getSupportFragmentManager();
FragmentTransaction xxtransaction = xxmanager.beginTransaction();
xxtransaction.replace(R.id.frame,AlxxlContact);
xxtransaction.addToBackStack(null);
xxtransaction.commit();
toolbar.setTitle("Special Contact");
return true;
}
return true;
}
});
}
#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_main, menu);
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
MenuItem menuItem =menu.findItem(R.id.search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(this);
return true;
}
#Override
protected void onResume() {
super.onResume();
}
#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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onQueryTextSubmit(String query) {
int id = navigationView.getSelectedItemId();
switch (id)
{
case R.id.action_MyNotes:
Fragment NoteFrgment = new NotesFrag();
((NotesFrag) NoteFrgment).onQueryTextSubmit(query);
case R.id.action_AllContact:
Fragment AllCont = new AllContactFrag();
((AllContactFrag) AllCont).onQueryTextSubmit(query);
return true;
case R.id.action_Spec :
Fragment Spec = new SpecialContactFrag();
((SpecialContactFrag) Spec).onQueryTextSubmit(query);
}
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// Toast.makeText(getBaseContext(),newText,Toast.LENGTH_LONG).show();
SearchText = newText ;
int id = navigationView.getSelectedItemId();
switch (id)
{
case R.id.action_MyNotes:
Fragment NoteFrgment = new NotesFrag();
((NotesFrag) NoteFrgment).onQueryTextChange(newText);
case R.id.action_AllContact:
AllContactFrag AllCont = (AllContactFrag)getSupportFragmentManager().findFragmentById(R.id.frame);
((AllContactFrag) AllCont).onQueryTextChange(newText);
return true;
case R.id.action_Spec :
Fragment Spec = new SpecialContactFrag();
((SpecialContactFrag) Spec).onQueryTextChange(newText);
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
allContactFrag.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
/* public class SectionsPagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragmentList = new ArrayList<>();
List<String> fragmentListTitle = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(LoadContact){
return fragmentList.get(position);
}else {
return fragmentList.get(position);
}
}
#Override
public int getCount() {
return fragmentList.size();
}
public void AddFragment(Fragment fragment, String fragmentTitle)
{
fragmentList.add(fragment);
fragmentListTitle.add(fragmentTitle);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentListTitle.get(position);
}
}
*/
}
//
#Override
public boolean onQueryTextChange(String newText) {
// Toast.makeText(getBaseContext(),newText,Toast.LENGTH_LONG).show();
SearchText = newText ;
int id = navigationView.getSelectedItemId();
switch (id)
{
case R.id.action_MyNotes:
Fragment NoteFrgment = new NotesFrag();
((NotesFrag) NoteFrgment).onQueryTextChange(newText);
case R.id.action_AllContact:
AllContactFrag AllCont = (AllContactFrag)getSupportFragmentManager().findFragmentById(R.id.frame);
((AllContactFrag) AllCont).onQueryTextChange(newText);
return true;
case R.id.action_Spec :
Fragment Spec = new SpecialContactFrag();
((SpecialContactFrag) Spec).onQueryTextChange(newText);
}
return true;
}
// at the fragment
#Override
public boolean onQueryTextSubmit(String s) {
Log.d("", "onQueryTextSubmit: ");
search_list = new ArrayList<>();
search_list.clear();
Context context = getContext();
db = new dbhandler(mcontext);
phoneList = new ArrayList<>();
phoneList = db.getAllPhoneContact();
String name;
contact contact = new contact();
for (int i = 0; i < phoneList.size(); i++)
{
contact = phoneList.get(i);
name = phoneList.get(i).getName();
if(name.contains(s))
{
search_list.add(contact);
}
}
allConAdapter = new AllConAdapter(getActivity(),search_list, 0);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(allConAdapter);
allConAdapter.notifyDataSetChanged();
return true ;
}
private Context mcontext;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mcontext = context ;
Log.d("", "onAttach: ");
}
at the fragment at onQueryTextSubmit the context value becomes null so the app crashes because I want to read data from SQLite and context is null

How Can I Update data in Recyclerview?

I Build an app that load data with Retrofit, into a recyclerview, my recyclerview load perfectly all data from JSON file, but when I try of an update with swipeRefreshLayout, and I intent load again the method loadFirstPage();, but simply add again the same data.
I search in google for any solution, but all my intents do not work in my code.
I intent used adapter.clear and load again, but not work fine.
The idea is if 1 item change from JSON file, update again the data in Recyclerview.
public class historial extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
User user = SharedPrefManager.getInstance(this).getUser();
private static final String TAG = "MainActivity";
PaginationAdapter adapter;
LinearLayoutManager linearLayoutManager;
private SwipeRefreshLayout swipeRefreshLayout;
RecyclerView recyclerView;
ProgressBar progressBar;
private static final int PAGE_START = 1;
private boolean isLoading = false;
private boolean isLastPage = false;
// limiting to 5 for this tutorial, since total pages in actual API is very large. Feel free to modify.
private int TOTAL_PAGES = 5;
private int currentPage = PAGE_START;
private NetworkInterface geosInterface;
int position;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.historial);
Toolbar toolbar = findViewById(R.id.toolbar);
//setting the title
toolbar.setTitle("elGEos School - Historial");
//placing toolbar in place of actionbar
setSupportActionBar(toolbar);
progressBar = findViewById(R.id.progressBar);
recyclerView = findViewById(R.id.recycler_view);
adapter = new PaginationAdapter(this);
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(historial.this);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new PaginationScrollListener(linearLayoutManager) {
#Override
protected void loadMoreItems() {
isLoading = true;
currentPage += 1;
// mocking network delay for API call
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
loadNextPage();
}
}, 1000);
}
#Override
public int getTotalPageCount() {
return TOTAL_PAGES;
}
#Override
public boolean isLastPage() {
return isLastPage;
}
#Override
public boolean isLoading() {
return isLoading;
}
});
//init serecyclerViewice and load data
geosInterface = NetworkApi.getClient().create(NetworkInterface.class);
loadFirstPage();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
//CODE FOR UPDATE HERE ???
if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false); // This hides the spinner
}
}
});
}
//TOOL BAR Y MENU
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu3, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.aboutback:
onBackPressed();
//Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
private void loadFirstPage() {
swipeRefreshLayout.setRefreshing(true);
Log.d(TAG, "loadFirstPage: ");
callTopMessage().enqueue(new Callback<TopMessage>() {
#Override
public void onResponse(Call<TopMessage> call, Response<TopMessage> response) {
// Got data. Send it to adapter
List<Result> results = fetchResults(response);
progressBar.setVisibility(View.GONE);
adapter.addAll(results);
if (currentPage <= TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFailure(Call<TopMessage> call, Throwable t) {
t.printStackTrace();
// TODO: 08/11/16 handle failure
swipeRefreshLayout.setRefreshing(false);
}
});
}
/**
* #param response extracts List<{#link Result>} from response
* #return
*/
private List<Result> fetchResults(Response<TopMessage> response) {
TopMessage topMessage = response.body();
return topMessage.getResults();
}
private void loadNextPage() {
swipeRefreshLayout.setRefreshing(true);
Log.d(TAG, "loadNextPage: " + currentPage);
callTopMessage().enqueue(new Callback<TopMessage>() {
#Override
public void onResponse(Call<TopMessage> call, Response<TopMessage> response) {
adapter.removeLoadingFooter();
isLoading = false;
List<Result> results = fetchResults(response);
adapter.addAll(results);
if (currentPage != TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFailure(Call<TopMessage> call, Throwable t) {
t.printStackTrace();
// TODO: 08/11/16 handle failure
swipeRefreshLayout.setRefreshing(false);
}
});
}
private Call<TopMessage> callTopMessage() {
return geosInterface.getTopMessage(
"Comfama",
"B",
"TTY651",
"1",
currentPage
);
}
#Override
public void onRefresh() {
}
}
Try this:
it is very simple to update and remove data in recycler view
REMOVE Data : There are 4 steps to remove an item from a RecyclerView adapter class like this:
list.remove(position);
recycler.removeViewAt(position);
adapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, list.size());
make sure your data is set in adapter class like this after that you notifyData
private void setAdapter() {
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recycler_view.setLayoutManager(mLayoutManager);
mAdapter = new BankDetailsAdapter(getBankList,this);
recycler_view.setAdapter(mAdapter);
}
UPDATE data: There are 1 steps to update data like this:
adapter.notifyDataSetChanged();
it helps you

OrmLite get value from listView with Adapter

When I want to get a name of list which I pressed, I get "com.example.oleksandr.dream.DB.DreamDetails#528f8a90". How can I get a String value from my list? The problem is in "the onItemClick" methode.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DBHelper mDbHelper = null;
private DreamDetails dreamDetails;
private ListView mListView;
private DrawerLayout drawerLayout;
private Toolbar mToolbar;
private Dao<DreamDetails, Integer> dreamDetailsDao;
private List<DreamDetails> dreamList;
private int selectedRecordPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listViewAllDreams);
try {
//Getting all Data from DB
dreamDetailsDao = getHelper().getDreamDetailsesDao();
dreamList = dreamDetailsDao.queryForAll();
// Set the header of the ListView
final LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.list_view, mListView, false);
mListView.addHeaderView(view);
// my own adapter!
mListView.setAdapter(new AdapterArrayDream(this,R.layout.list_view,dreamList,dreamDetailsDao));
mListView.setOnItemClickListener(this);
} catch (SQLException e) {
e.printStackTrace();
}
initToolbar();
initNavigationView();
FloatingActionButton myFab = (FloatingActionButton)findViewById(R.id.fab);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewDream.class);
startActivity(intent);
}
});
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(i > 0)
{
selectedRecordPosition = i - 1;
// final Intent intent = new Intent(this, ViewDream.class);
Log.i("TAAAAAAG", "onClick " + adapterView.getItemAtPosition(selectedRecordPosition));
// intent.putExtra("D", String.valueOf(adapterView.getItemAtPosition(selectedRecordPosition)));
// startActivity(intent);
}
}
private void initNavigationView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawlerLayout);
}
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(R.string.app_name);
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
// mToolbar.inflateMenu(R.menu.menu);
}
// This is how, DatabaseHelper can be initialized for future use
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_list_dreams, menu);
return true;
}
private DBHelper getHelper() {
if (mDbHelper == null) {
mDbHelper = OpenHelperManager.getHelper(this, DBHelper.class);
}
return mDbHelper;
}
}
To create a query which looks up an account by name and password you would do the following:
QueryBuilder<Account, String> qb = accountDao.queryBuilder();
Where where = qb.where();
// the name field must be equal to "foo"
where.eq(Account.NAME_FIELD_NAME, "foo");
// and
where.and();
// the password field must be equal to "_secret"
where.eq(Account.PASSWORD_FIELD_NAME, "_secret");
PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();

delete a dynamically created button android

Ok, what I'm trying to do is, something like a tag search function.
What I did was create Button ArrayList, and whenever a user tries to input ",", it automatically creates a button and inserts it into the ArrayList, which ultimately registers to the LinearLayout.
It creates well, but does not delete well.
I get the error that the index is out of bounds, but was in no luck of finding out which statement should I use. Could you help me?
Thx in advance.
public class MainActivity extends AppCompatActivity {
private ArrayList<Button> tagCollection = null;
private LinearLayout llTagCollection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tagCollection = new ArrayList<Button>();
initView();
}
#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_main, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void initView() {
final EditText etSearch = (EditText) findViewById(R.id.ET_SEARCH);
// final TextView tvResult = (TextView) findViewById(R.id.TV_RESULT);
llTagCollection = (LinearLayout) findViewById(R.id.LL_BUTTON_COLLECTION);
View currentView = new View(getApplicationContext());
/*
if(tagCollection.size() != 0) {
tagCollection.get(currentView.getId()).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tagCollection.remove(tagCollection.get(v.getId()));
Log.e("Removed", String.valueOf(tagCollection.remove(tagCollection.get(v.getId()))));
// tagCollection.remove(this);
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
llTagCollection.addView(tagCollection.get(i));
i += 1;
}
}
});
}
*/
TextWatcher tagWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String convertedCharSequence = s.toString();
Log.e("ConvertedString", convertedCharSequence);
if (convertedCharSequence.length() > 0) {
String subString = convertedCharSequence.substring(convertedCharSequence.length() - 1);
Log.e("SubStringPosition", subString);
if (subString.equals(",")) {
// tvResult.setText(etSearch.getText().toString());
Button bTagButton = new Button(MainActivity.this);
bTagButton.setId(tagCollection.size());
bTagButton.setText(etSearch.getText().toString());
bTagButton.setBackgroundColor(Color.WHITE);
bTagButton.setTextColor(Color.BLACK);
/*
RelativeLayout.LayoutParams rlLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if(tagCollection.size() != 0){
rlLayoutParams.addRule(RelativeLayout.END_OF, tagCollection.get(0).getId());
}
bTagButton.setLayoutParams(rlLayoutParams);
*/
bTagButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tagCollection.remove(tagCollection.indexOf(this));
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
if(tagCollection.get(i) != null){
llTagCollection.addView(tagCollection.get(i));
}
i += 1;
}
}
});
tagCollection.add(bTagButton);
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
llTagCollection.addView(tagCollection.get(i));
i += 1;
}
// setContentView(rlTagCollection);
etSearch.setText("");
etSearch.setSelection(0);
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
etSearch.addTextChangedListener(tagWatcher);
}
}
I solved it using indexOfChild function. It kept on throwing me indexOutOfBounds error. Thx
Because of the reputations, I can not add comment. SO I post here.
In the button click listener:
bTagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tagCollection.remove(tagCollection.indexOf(this));
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
if (tagCollection.get(i) != null) {
llTagCollection.addView(tagCollection.get(i));
}
i += 1;
}
}
});
You remove the button by tagCollection.remove(tagCollection.indexOf(this));. Here this means the OnClickListener instance, not the button clicked. SO you should remove buttons by:
tagCollection.remove(tagCollection.indexOf(v));

Open New Activity by id on Listview Item Click

My ListView is opening and everything is ok. I don´t know how to pass params from onPostExecute() to onItemClick() to open a new activity (SingleItem.java) by id.
Nothing that I´ve tried has worked.
ListItems.java
public class ListItems extends Activity {
private ListView listV;
TextView estado, cidade, noItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_items);
listV = (ListView) findViewById(R.id.listV);
estado = (TextView) findViewById(R.id.Estado);
cidade = (TextView) findViewById(R.id.Cidade);
noItem = (TextView) findViewById(R.id.noItem);
estado.setText(getIntent().getExtras().getString("state"));
cidade.setText(getIntent().getExtras().getString("city"));
Task task = new Task();
task.execute();
listV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getApplicationContext(), SingleItem.class);
startActivity(intent);
}
});
}
public class Task extends AsyncTask<String, String, Void>{
private ProgressDialog progressDialog = new ProgressDialog(ListItems.this);
InputStream is = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Listing Items...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
Task.this.cancel(true);
}
});
};
#Override
protected Void doInBackground(String... params) {
String url = "http://myip/webviews/jsonlistItems.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error connecting to database " + e.toString());
Toast.makeText(ListItems.this, "Try again.", Toast.LENGTH_LONG).show();
}
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line = br.readLine()) != null){
sb.append(line+"\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v){
try {
JSONArray Jarray = new JSONArray(result);
for (int i = 0; i < Jarray.length(); i++) {
JSONObject jsonObject = null;
jsonObject = Jarray.getJSONObject(i);
// output
String item_id = jsonObject.getString("item_id");
String item_name = jsonObject.getString("item_name");
String item_color = jsonObject.getString("item_color");
String city = jsonObject.getString("city");
String statee = jsonObject.getString("state");
if(estado.getText().toString().equalsIgnoreCase(statee) &&
cidade.getText().toString().equalsIgnoreCase(city)){
String[] values = new String[] {item_name, item_color};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListItems.this, android.R.layout.simple_list_item_1, values);
listV.setAdapter(adapter);
break;
}
else{
noItem.setText("No Item to show");
}
}
this.progressDialog.dismiss();
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
public class ItemById{
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list_events, 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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
SingleItem.java
public class SingleItem extends Activity {
TextView item_name, item_color;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleitem);
item_name = (TextView) findViewById(R.id.item_name);
item_color = (TextView) findViewById(R.id.item_color);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.event, 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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
How to pass params from onPostExecute() to onItemClick() to open a new activity (SingleItem.java) by id?
It all depends what your SingleItem Activity is supposed to show when it's opened.
If you only need the name of the selected item then you simply retrieve the item name in the onItemClick method and pass it as parameter to SingleItem:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), SingleItem.class);
String name = adapter.getItem(position);
intent.putExtra("yourItem", name);
startActivity(intent);
}
In order for this to work the adapter needs to be a variable in the Activity:
public class ListItems extends Activity {
private ArrayAdapter<String> adapter;
and this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListItems.this, android.R.layout.simple_list_item_1, values);
becomes this:
adapter = new ArrayAdapter<String>(ListItems.this, android.R.layout.simple_list_item_1, values);
If you need more information in the SingleItem Activity than just the name of the item you'd have to create an Item class to hold that information:
public static class Item implements Serializable {
String mName;
String mColor;
// more data
#Override
public String toString() {
return mName;
}
}
your onItemClick becomes:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), SingleItem.class);
Item item = adapter.getItem(position);
intent.putExtra("yourItem", name);
startActivity(intent);
}
Your adapter would be:
ArrayAdapter<Item> adapter;
adapter = new ArrayAdapter<Item>(ListItems.this, android.R.layout.simple_list_item_1, itemArray);
Of course you'd need to create the itemArray when parsing the json stream.
The activity could easily read the selected item from the intent like so:
getIntent().getSerializableExtra("yourItem");
The adapter looks like it's populated only by each attribute of your JSON object (one row for item_name, one row for item_color). If this is what you want the naturally you won't get item_id because it's not there.
If you want each row to correspond to each of your JSON objects then you should modify your adapter.
First make your own class like so
class Wrap{
String itemId, itemName, city, statee;
}
And then create your own Adapter class that extends ArrayAdapter<Wrap>.
This way every time a row is clicked, you can get the Wrap object which contains everything, including id. Then you can pass these values to your next Activity.

Categories

Resources