I migrated from the old Places SDK to the new Places SDK (including writing a new adapter), and now when typing an address into my AutoCompleteTextView it shows only the Place Names in the drop-down list (i.e. addresses but without city, state, country), but I need it to show the full address.
Here is my adapter:
import android.content.Context;
import android.graphics.Typeface;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import java.util.List;
public class PlaceAutocompleteAdapterNew extends ArrayAdapter<AutocompletePrediction> implements Filterable
{
PlacesClient placesClient;
AutocompleteSessionToken token;
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
private List<AutocompletePrediction> mResultList;
private List<AutocompletePrediction> tempResult;
Context context;
private String TAG="PlaceAutoCompleteAdapter";
public PlaceAutocompleteAdapterNew(Context context,PlacesClient placesClient,AutocompleteSessionToken token) {
super(context,android.R.layout.simple_expandable_list_item_1,android.R.id.text1);
this.context=context;
this.placesClient=placesClient;
this.token=token;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
AutocompletePrediction item = getItem(position);
TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
textView1.setText(item.getPrimaryText(STYLE_BOLD));
return row;
}
#Override
public int getCount() {
return mResultList.size();
}
#Override
public AutocompletePrediction getItem(int position) {
return mResultList.get(position);
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// Skip the autocomplete query if no constraints are given.
if (constraint != null) {
// Query the autocomplete API for the (constraint) search string.
mResultList = getAutoComplete(constraint);
if (mResultList != null) {
// The API successfully returned results.
results.values = mResultList;
results.count = mResultList.size();
}
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
notifyDataSetInvalidated();
}
}
#Override
public CharSequence convertResultToString(Object resultValue) {
// Override this method to display a readable result in the AutocompleteTextView
// when clicked.
if (resultValue instanceof AutocompletePrediction) {
return ((AutocompletePrediction) resultValue).getFullText(null);
} else {
return super.convertResultToString(resultValue);
}
}
};
}
private List<AutocompletePrediction> getAutoComplete(CharSequence constraint){
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
// and once again when the user makes a selection (for example when calling fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
// Create a RectangularBounds object.
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// Call either setLocationBias() OR setLocationRestriction().
//.setLocationBias(bounds)
//.setLocationRestriction(bounds)
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(constraint.toString())
.build();
placesClient.findAutocompletePredictions(request).addOnSuccessListener(new OnSuccessListener<FindAutocompletePredictionsResponse>() {
#Override
public void onSuccess(FindAutocompletePredictionsResponse response) {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPrimaryText(null).toString());
}
tempResult=response.getAutocompletePredictions();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + apiException.getStatusCode());
}
}
});
return tempResult;
}
}
How can I show the full addresses in the drop-down list?
getAutoComplete is returning tempResult. This is a List that contains fullText (the full address), primaryText (just the address without city, state, country), and other items. So the fullText is what I want, which is being returned, but the primaryText is what is being displayed in the AutoCompleteTextView. How can I fix this?
I changed this line:
textView1.setText(item.getPrimaryText(STYLE_BOLD));
to this:
textView1.setText(item.getFullText(STYLE_BOLD));
Related
I have a problem i can't solve and I have spent a lot of time. I have a table and I have a column with hyperlinks. I have some filters added to the table and when I activate one of those filters, the hyperlink column doesn't refresh correctly. The code I implemented is showing above. This is an example you can copy&paste, run & reproduce the bug:
The Table class:
package borrar;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.Hyperlink;
public class Example {
private static TableViewer tViewer = null;
private static Table tblTrades = null;
private static Text txtTicker;
public static TickerFilter2 tickerFilter = new TickerFilter2();
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Composite parent = new Composite(shell, SWT.NONE);
parent.setLayout(new FillLayout());
parent.setLayout(new GridLayout(1, true));
Label lblTicker = new Label(parent, SWT.NONE);
lblTicker.setText("Search: ");
txtTicker = new Text(parent, SWT.NONE);
txtTicker.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtTicker.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
tickerFilter.setSearchText(txtTicker.getText());
tViewer.refresh();
}
});
tViewer = new TableViewer(parent, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION | SWT.CENTER);
String[] titles = { "Ticker", "Hyperlinks" };
createColumns(titles);
tblTrades = tViewer.getTable();
tViewer.setContentProvider(new ArrayContentProvider());
List<DataTable> dt = Arrays.asList(new DataTable("AAA", "ImagePath"), new DataTable("ABBBBBB", "ImagePath"),
new DataTable("BBBBBBB", "ImagePath"));
tViewer.setInput(dt);
tblTrades.setHeaderVisible(true);
tViewer.addFilter(tickerFilter);
shell.open();
shell.pack();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private static void createColumns(String[] titles) {
TableViewerColumn col = createTableViewerColumn(titles[0], 70);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
DataTable op = (DataTable) element;
if (op.getTicker() != null) {
return op.getTicker();
} else {
return "";
}
}
});
col = createTableViewerColumn(titles[1], 80);
col.setLabelProvider(new ColumnLabelProvider() {
Map<Object, Hyperlink> hyperlinks = new HashMap<Object, Hyperlink>();
#Override
public void update(ViewerCell cell) {
TableItem item = (TableItem) cell.getItem();
final Hyperlink hyperlink;
if (hyperlinks.containsKey(cell.getElement()) && !hyperlinks.get(cell.getElement()).isDisposed()) {
hyperlink = hyperlinks.get(cell.getElement());
} else {
hyperlink = new Hyperlink((Composite) (cell.getViewerRow().getControl()), SWT.NONE);
if (cell.getElement() instanceof DataTable) {
DataTable trade = (DataTable) cell.getElement();
if (trade.getPath() != null && !trade.getPath().equals("")) {
hyperlink.setText(trade.getPath() + "-" + trade.getTicker());
hyperlink.setHref(trade.getPath());
}
}
hyperlink.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
org.eclipse.swt.program.Program.launch(hyperlink.getHref().toString());
}
});
hyperlinks.put(cell.getElement(), hyperlink);
}
TableEditor editor = new TableEditor(item.getParent());
editor.grabHorizontal = true;
editor.grabVertical = true;
editor.setEditor(hyperlink, item, cell.getColumnIndex());
editor.layout();
}
});
}
private static TableViewerColumn createTableViewerColumn(String title, int bound) {
final TableViewerColumn viewerColumn = new TableViewerColumn(tViewer, SWT.CENTER);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
public void refreshTable() {
tViewer.refresh();
}
}
My filter class:
package borrar;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
public class TickerFilter2 extends ViewerFilter {
private String searchString;
public void setSearchText(String s) {
// ensure that the value can be used for matching
this.searchString = ".*" + s + ".*";
}
#Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (searchString == null || searchString.length() == 0) {
return true;
}
DataTable trade = (DataTable) element;
if (trade.getTicker().matches(searchString)) {
return true;
}
return false;
}
}
The data table object:
package borrar;
public class DataTable {
String ticker;
String path;
public DataTable(String ticker, String path) {
super();
this.ticker = ticker;
this.path = path;
}
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
If you put in the search field a "z" or "l" for example, you can see that the hyperlink column does not filter.
The filter class filters data correctly but the hyperlinks column doesn't filter fine.
Here you have an image with the bad result:
The TableViewer doesn't really know about the TableEditor code so it doesn't deal with them when filtering.
You could perhaps use the EditingSupport code. The following code defines a cell editor which does an action as soon as you click on the column cell.
For the column definition replace your code with something like:
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(final Object element) {
// Whatever you want for the cell text here
final DataTable op = (DataTable) element;
return op.getPath();
}
});
col.setEditingSupport(new HyperlinkEditingSupport(tViewer));
The editing support class:
public class HyperlinkEditingSupport extends EditingSupport
{
private final HyperlinkCellEditor _editor;
public HyperlinkEditingSupport(final TableViewer viewer)
{
super(viewer);
_editor = new HyperlinkCellEditor(viewer.getTable());
}
#Override
protected CellEditor getCellEditor(final Object element)
{
return _editor;
}
#Override
protected boolean canEdit(final Object element)
{
return true;
}
#Override
protected Object getValue(final Object element)
{
// Return the value you want launched
return ((DataTable)element).getPath();
}
#Override
protected void setValue(final Object element, final Object value)
{
// no action
}
}
And the CellEditor. This is a bit odd because we are just going to launch as soon as the editor is invoked so we don't really need a separate editor:
public class HyperlinkCellEditor extends CellEditor
{
public HyperlinkCellEditor(final Composite parent)
{
super(parent);
}
#Override
protected Control createControl(final Composite parent)
{
return new Composite(parent, SWT.None);
}
#Override
protected Object doGetValue()
{
return new Object[0];
}
#Override
protected void doSetFocus()
{
// no action
}
#Override
protected void doSetValue(final Object value)
{
final String path = (String)value;
// TODO Open the link
}
}
I have modified #greg-449 solution to show a link appearance in the cell only modifying the LabelProvider:
col.setLabelProvider(new StyledCellLabelProvider() {
#Override
public void update(ViewerCell cell) {
DataTable op = (DataTable) cell.getItem().getData();
StyledString ss = new StyledString();
StyleRange sr = new StyleRange(0, 80, Display.getCurrent().getSystemColor(SWT.COLOR_BLUE), null);
sr.underline = true;
ss.append(op.getPath(), StyledString.DECORATIONS_STYLER);
cell.setText("Open Image");
StyleRange[] range = { sr };
cell.setStyleRanges(range);
}
});
col.setEditingSupport(new HyperlinkEditingSupport(tViewer));
when i filter recyclerview it shows Not found .My Searchview not working.when i run the code its result in Not Found i think there is problem in onQueryTextChange
myfilter function also did not work
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(SecondActivity1.this, "Name is : " + query, Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DatabaseModel> filteredModelList = filter(dbList, newText);
if (filteredModelList.size() > 0) {
// Toast.makeText(SecondActivity1.this, "Found", Toast.LENGTH_SHORT).show();
recyclerAdapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(SecondActivity1.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
private List filter(List models, String query) {
query = query.toLowerCase();
recyclerAdapter.notifyDataSetChanged();
final List<DatabaseModel> filteredModelList = new ArrayList<>();
// mRecyclerView.setLayoutManager(new LinearLayoutManager(SecondActivity1.this));
// mRecyclerView.setAdapter(RecyclerAdapter);
for (DatabaseModel model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
//
}
here is filter method which recieve parameter(dblist,newtext) filter method recieves these method when i use toast its show that it takes newText But didnot filter this.i checked many sites but this is same in many sites points.when i enter name toast shows name which i enter but it did not filter
RecyclerAdapter.java
package com.example.prabhu.databasedemo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user_adnig on 11/14/15.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
List<DatabaseModel> dbList;
static Context context;
RecyclerAdapter(Context context, List<DatabaseModel> dbList ){
this.dbList = new ArrayList<>();
this.context = context;
this.dbList = (ArrayList<DatabaseModel>) dbList;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
holder.name.setText(dbList.get(position).getName());
holder.email.setText(dbList.get(position).getEmail());
}
#Override
public int getItemCount() {
return dbList.size();
}
public void setFilter(List<DatabaseModel> countryModels) {
// Toast.makeText(RecyclerAdapter.this,"Method is called", Toast.LENGTH_SHORT).show();
dbList = new ArrayList<>();
dbList.addAll(countryModels);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name,email;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
name = (TextView) itemLayoutView
.findViewById(R.id.rvname);
email = (TextView)itemLayoutView.findViewById(R.id.rvemail);
itemLayoutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailsActivity.class);
Bundle extras = new Bundle();
extras.putInt("position",getAdapterPosition());
intent.putExtras(extras);
/*
int i=getAdapterPosition();
intent.putExtra("position", getAdapterPosition());*/
context.startActivity(intent);
Toast.makeText(RecyclerAdapter.context, "you have clicked Row " + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
}
}
this is my recyclerAdapterCode.i also used Recycleradapter.setFilter(filterModeList) method but it did not work for me.i think in my set filter method error which i did not solve yet.
. But when I clear the search widget I don't get the full list instead I get the empty RecyclerView.
I have created a custom adapter that extends ArrayAdapter containing Listview with two TextView in a single row. I have SearchView on the ActionBar.In onQueryTextChange(String s) i have tried some methods which i have found, works but result is not correct, in the end i have only first row from ListView. How to make SearchView to work correctly?
Everything else working fine. This app is for minSdkVersion="9" and above. Any suggestion will be OK. Regards.
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.TextView;
public class A extends ActionBarActivity{
ListView list;
String[] titl;
String[] opis;
SearchView searchView;
VjuAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
ActionBar aB = getSupportActionBar();
aB.setDisplayHomeAsUpEnabled(true);
Resources res=getResources();
titl=res.getStringArray(R.array.naslov);
opis=res.getStringArray(R.array.podnaslov);
list=(ListView) findViewById(R.id.listView);
VjuAdapter adapter=new VjuAdapter(this, titl, opis);
adapter.getFilter().filter(null);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater men = getMenuInflater();
men.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.trazi);
ComponentName cn = new ComponentName(this, A.class);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));
//searchView.setOnQueryTextListener(this);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String s) {
// Here i have tried some methods which i have found
// this works but result is not correct, in the end i have
// only first row from ListView
/*if (TextUtils.isEmpty(s)) {
((LayoutInflater) list.getAdapter()).getFilter().filter(s);
} else {
adapter.getFilter().filter(s.toString());
}
return true;
}
});*/
//s.toLowerCase(Locale.getDefault());
VjuAdapter vd = (VjuAdapter)list.getAdapter();
Ll.m("POCETAK VD "+ vd);
Filter filter = vd.getFilter();
Ll.m("SRED VD.GET "+ vd.getFilter());
filter.filter(s);
Ll.m("KRAJ FILTER "+ filter);
/*if (TextUtils.isEmpty(s)) {
list.clearTextFilter();
} else {
//adapter.setSelectionAfterHeaderView();
adapter.getFilter().filter(s.toString());
}*/
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
int id = item.getItemId();
/*if (id == R.id.trazi){
onSearchRequested();
}*/
if (id == android.R.id.home){
onBackPressed();
}
if (id == R.id.about){
Intent i = new Intent("com.kanna.sanjarica.ABOUT");
startActivity(i);
}
if (id == R.id.oceni_apl){
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
startActivity(goToMarket);
}
if (id == R.id.kontakt){
String mailTo="kanjah77#gmail.com";
Intent email_intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",mailTo, null));
email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
email_intent.putExtra(android.content.Intent.EXTRA_TEXT,"");
startActivity(Intent.createChooser(email_intent, "PoĊĦalji email..."));
}
return true;
}
}
class VjuAdapter extends ArrayAdapter<String>{
Context context;
String [] titlArray;
String [] opisArray;
public VjuAdapter(Context c, String[] naslov, String[] podnaslov ) {
super(c,R.layout.single_row,R.id.textView1,naslov);
this.context=c;
this.titlArray=naslov;
this.opisArray=podnaslov;
}
class MyViewHolder{
TextView textVel;
TextView textMal;
MyViewHolder(View v){
textVel=(TextView) v.findViewById(R.id.textView1);
textMal=(TextView) v.findViewById(R.id.textView2);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
MyViewHolder holder=null;
if(row==null){
LayoutInflater inf=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inf.inflate(R.layout.single_row, parent, false);
holder=new MyViewHolder(row);
row.setTag(holder);
}else{
holder=(MyViewHolder) row.getTag();
}
holder.textVel.setText(titlArray[position]);
holder.textMal.setText(opisArray[position]);
return row;
}
}
This is from http://developer.android.com/:
A concrete BaseAdapter that is backed by an array of arbitrary
objects. By default this class expects that the provided resource id
references a single TextView. If you want to use a more complex
layout, use the constructors that also takes a field id. That field id
should reference a TextView in the larger layout resource.
You have 2 TextView, and constructor class is this:
ArrayAdapter(Context context, int resource, int textViewResourceId)
I am new in creating apps. I am learning by doing courses on Udemy. So right now I am learning how to create a simple app where your can register, login and post a message, and I am doing all of this using Parse.com. Everything worked perfectly until today, when it was time to create a custom adapter that shows these posts.
The error is: cannot resolve symbol mStatus in the HomepageActivity class, though in the Udemy video, everything works perfectly.
Another strange error is in the line
ParseQuery<ParseObject> query = new ParseQuery <ParseObject> ("Status");
the second <ParseObject> is greyed out and it says Explicit type argument can be replaced with <>, though in the video its white(working).
The only explanation I thought of is that the video is old and something changed in the syntax, but I am not that great of a programmer to understand what to do. Or maybe im doing something wrong? Please help.
P.S . when I am trying to run the app, I am getting this message:
Note:C:\Users\User\AndroidStudioProjects\LiveUpdate\app\src\main\java\com\mycompany\liveupdate\StatusAdapter.java uses unchecked or unsafe operations.
Here is the adapter code:
package com.mycompany.liveupdate;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.parse.ParseObject;
import java.util.List;
/**
* Created by User on 2015-01-18.
*/
public class StatusAdapter extends ArrayAdapter {
protected Context mContext;
protected List<ParseObject> mStatus;
public StatusAdapter(Context context, List status) {
super(context, R.layout.homepagecustomlayout, status);
mContext = context;
mStatus = status;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.homepagecustomlayout, null);
holder = new ViewHolder();
holder.usernameHomepage = (TextView) convertView
.findViewById(R.id.usernameHP);
holder.statusHomepage = (TextView) convertView
.findViewById(R.id.statusHP);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseObject statusObject = mStatus.get(position);
// title
String username = statusObject.getString("user");
holder.usernameHomepage.setText(username);
// content
String status = statusObject.getString("newStatus");
holder.statusHomepage.setText(status);
return convertView;
}
public static class ViewHolder {
TextView usernameHomepage;
TextView statusHomepage;
}
}
Here is the code, where im trying to call this adapter:
package com.mycompany.liveupdate;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.List;
public class HomepageActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Parse.initialize(this, "uinXCHcfbdm8zrbUT9y8Vu4R2qU5D22FZwkHs5HZ", "v1PL4oDu3ebtSidJFhjWRkkBQVAD8sefIB1WDFeq");
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
// show user the homepage
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Status");
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> status, ParseException e) {
if(e == null){
//success
mStatus = status;
StatusAdapter adapter = new StatusAdapter(getListView().getContext(), status);
setListAdapter(adapter);
}else {
//there was a problem
}
}
});
} else {
// show the signup or login screen
Intent takeUserToLogin = new Intent(HomepageActivity.this, LogInActivity.class);
startActivity(takeUserToLogin);
}
}
#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_homepage, 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();
switch (id){
case R.id.updateStatus:
//take user to updatestatus activity
Intent intent = new Intent(this, UpdateStatusActivity.class );
startActivity(intent);
break;
case R.id.logoutUser:
// log out user
ParseUser.logOut();
// take the user back to logout screen
Intent takeUserToLogin = new Intent(this, LogInActivity.class);
startActivity(takeUserToLogin);
break;
}
return super.onOptionsItemSelected(item);
}
}
I have found this code for searching for a specific user, using Parse. But when i run the code, it crashes.
What is wrong with the code???
The following is the link to the codes https://teamtreehouse.com/forum/tutorial-adding-search-to-ribbit-app
Here is the code
package com.twaa9l.isnap;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class EditFriendsActivity extends ListActivity {
public static final String TAG = EditFriendsActivity.class.getSimpleName();
protected List<ParseUser> mUsers;
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected EditText sUsername;
protected Button mSearchButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_edit_friends);
// Show the Up button in the action bar.
setupActionBar();
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
sUsername = (EditText)findViewById(R.id.searchFriend);
mSearchButton = (Button)findViewById(R.id.searchButton);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////The New Code for Search Users by Username///////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get text from each field in register
String username = sUsername.getText().toString();
//String password = mPassword.getText().toString();
///Remove white spaces from any field
/// and make sure they are not empty
username = username.trim();
//password = password.trim();
//Check if fields not empty
if(username.isEmpty()){
AlertDialog.Builder builder = new AlertDialog.Builder(EditFriendsActivity.this);
builder.setMessage(R.string.login_error_message)
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else{
//Login User
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", username);
query.orderByAscending(ParseConstants.KEY_USERNAME);
query.setLimit(200);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
setProgressBarIndeterminateVisibility(false);
if(e == null){
//Success we have Users to display
//Get users match us
mUsers = users;
//store users in array
String[] usernames = new String[mUsers.size()];
//Loop Users
int i = 0;
for(ParseUser user : mUsers){
usernames[i] = user.getUsername();
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
EditFriendsActivity.this,
android.R.layout.simple_list_item_checked,
usernames
);
setListAdapter(adapter);
addFriendCheckmarks();
}
else{
//No Users to Display
Log.e(TAG, e.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(EditFriendsActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(getListView().isItemChecked(position)){
//Add Friends
mFriendsRelation.add(mUsers.get(position));
}
else{
//Remove Friend
mFriendsRelation.remove(mUsers.get(position));
}
mCurrentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e != null){
Log.e(TAG, e.getMessage());
}
}
});
}
private void addFriendCheckmarks(){
mFriendsRelation.getQuery().findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> friends, ParseException e) {
if(e == null){
//List Returned - look for a match
for(int i = 0; i < mUsers.size(); i++){
ParseUser user = mUsers.get(i);
for(ParseUser friend : friends){
if(friend.getObjectId().equals(user.getObjectId())){
//we have a match
getListView().setItemChecked(i, true);
}
}
}
}
else{
Log.e(TAG, e.getMessage());
}
}
});
}
}