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());
}
}
});
}
}
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.
This is my SignUp.class I want to upload a profile picture drawable into User class in the profilepic column and a profile cover in the profilecover column
R.drawable.avatar_circle is the profile picture drawable and R.drawable.drawer_header_light is the drawable for the profile cover.
package com.addict.secret;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import de.hdodenhof.circleimageview.CircleImageView;
public class SignUp extends AppCompatActivity {
ProgressDialog login;
ProgressDialog progress;
EditText emailTxt, usernameTxt, passwordTxt, passwordConfirmTxt;
Button registerBtn, termsBtn, aboutBtn;
CheckBox mcheckbox;
ParseUser User = new ParseUser();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
Toolbar toolbar = (Toolbar) findViewById(R.id.appBar_reset);
toolbar.setTitle(R.string.title_activity_sign_up);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabprof);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new AlertDialog.Builder(SignUp.this, R.style.AppCompatAlertDialogStyle)
.setIcon(R.drawable.ic_new_releases_black_24dp)
.setTitle(R.string.comingsoontitle)
.setMessage(getResources().getString(R.string.comingsoon))
.setNegativeButton(android.R.string.ok, null)
.create().show();
}
});
//termsBtn = (Button) findViewById(R.id.termsBtn);
//termsBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// TermsDialogFragment dialog = TermsDialogFragment.newInstance();
// dialog.show(getSupportFragmentManager(), "DialogFragment");
// }
// });
//aboutBtn = (Button) findViewById(R.id.aboutBtn);
//aboutBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// startActivity(new Intent(SignUp.this, About.class));
// }
// });
emailTxt = (EditText) findViewById(R.id.email);
usernameTxt = (EditText) findViewById(R.id.Username);
passwordTxt = (EditText) findViewById(R.id.password);
passwordConfirmTxt = (EditText) findViewById(R.id.passwordConfirm);
registerBtn = (Button) findViewById(R.id.registerBtn);
//Snackbar.make(context,getResources().getString(R.string.accept_notification);
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailTxt.getText().toString();
String username = usernameTxt.getText().toString();
String password = passwordTxt.getText().toString();
String passwordConfirm = passwordConfirmTxt.getText().toString();
Log.d("email", email);
Log.d("username", username);
Log.d("password", password);
Log.d("password confirm", passwordConfirm);
if (username.equals("")){
Toast.makeText(SignUp.this, R.string.signup_error_message_username, Toast.LENGTH_SHORT).show();
}
else if (email.equals("")){
Toast.makeText(SignUp.this, R.string.signup_error_message_email, Toast.LENGTH_SHORT).show();
}
else if (password.equals("") || password.length() < 6){
Toast.makeText(SignUp.this, R.string.signup_error_message_password6, Toast.LENGTH_SHORT).show();
}
else if (!passwordConfirm.equals(password)){
Toast.makeText(SignUp.this, R.string.signup_error_message_password, Toast.LENGTH_SHORT).show();
}
else {
progress = new ProgressDialog(SignUp.this, R.style.AppCompatAlertDialogStyle);
progress.setTitle(R.string.signup_dialog_title);
progress.setMessage(getResources().getString(R.string.signup_message));
progress.setCanceledOnTouchOutside(false);
progress.show();
registration(username, email, password);
}
}
});
}
private void registration(final String username, String email, final String password){
ParseGeoPoint currentLocation = new ParseGeoPoint(49.2827, -123.1207);;
User.setUsername(username);
User.put("status", getResources().getString(R.string.default_status));
User.setEmail(email);
User.setPassword(password);
User.put("Location", currentLocation);
User.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
progress.dismiss();
Toast.makeText(SignUp.this, R.string.success_signup, Toast.LENGTH_SHORT).show();
signInUser(username, password);
SignUp.this.finish();
} else {
progress.dismiss();
final Dialog dialog = new Dialog(SignUp.this, R.style.AppCompatAlertDialogStyle);
dialog.setContentView(R.layout.dialog_error);
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.message);
text.setText(R.string.signup_error_parse);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.error_fox);
Button dialogButton = (Button) dialog.findViewById(R.id.ok);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
});
}
private void signInUser(String username, String password){
login = new ProgressDialog(SignUp.this, R.style.AppCompatAlertDialogStyle);
login.setTitle(R.string.login_title);
login.setMessage(getResources().getString(R.string.login_message));
login.setCanceledOnTouchOutside(false);
login.show();
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
login.dismiss();
Toast.makeText(SignUp.this, R.string.success_login, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignUp.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(SignUp.this, R.string.error_login, Toast.LENGTH_SHORT).show();
}
}
});
}
#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_sign_up, 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);
}
}
First you should get the drawable and store it as a Bitmap:
Bitmap profilePic = BitmapFactory.decodeResource(context.getResources(), R.drawable.avatar_circle);
Bitmap profileCover = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_header_light);
Then when you're signing up the user:
ParseGeoPoint currentLocation = new ParseGeoPoint(49.2827, -123.1207);;
User.setUsername(username);
User.put("status", getResources().getString(R.string.default_status));
User.setEmail(email);
User.setPassword(password);
User.put("profilepic", profilePic);
User.put("profilecover", profileCover);
User.put("Location", currentLocation);
When I click on my app first button it stopped working
kindly advice,what can be the issue?
In my code,I am trying to open one layout when it button is click then is open another layout and then when its button is being clicked then is save data in database.
My loginActivity code is -
package com.example.ahmed.vehiclepermitapp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class LoginActivity extends Activity {
private static final int EDIT=0, DELETE=1;
EditText carTxt, statusTxt;
ImageView contactImageImgView;
List<Contact> Contacts = new ArrayList<Contact>();
ListView contactListView;
Uri imageUri=Uri.parse("android.resource://com.newthinktank.helloworld/drawable/search.png");
DatabaseHandler dbHandler;
int longClickItemIndex;
ArrayAdapter<Contact> contactAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final Button loginBtn = (Button) findViewById(R.id.btnLogin);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.activity_main);
carTxt = (EditText) findViewById(R.id.txtCar);
statusTxt = (EditText) findViewById(R.id.txtStatus);
contactListView = (ListView) findViewById(R.id.listView);
contactImageImgView = (ImageView) findViewById(R.id.imgViewContactImage);
dbHandler = new DatabaseHandler(getApplicationContext());
registerForContextMenu(contactListView);
contactListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickItemIndex = position;
return false;
}
});
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Creator");
tabSpec.setContent(R.id.Creator);
tabSpec.setIndicator("Creator");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("List");
tabSpec.setContent(R.id.List);
tabSpec.setIndicator("List");
tabHost.addTab(tabSpec);
final Button addBtn = (Button) findViewById(R.id.btnLogin);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact contact = new Contact(dbHandler.getContactCount(), String.valueOf(carTxt.getText()), String.valueOf(statusTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
contactAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), String.valueOf(carTxt.getText()) + " has been add to list", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getApplicationContext(), String.valueOf(carTxt.getText()) + "already exists. please use different name", Toast.LENGTH_SHORT).show();
}
});
carTxt.addTextChangedListener(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) {
addBtn.setEnabled(String.valueOf(carTxt.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
if (dbHandler.getContactCount() != 0)
Contacts.addAll(dbHandler.getAllContacts());
populateList();
}
});}
public void onCreateContextMenu(ContextMenu menu,View view,ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu,view,menuInfo);
menu.setHeaderIcon(R.drawable.pencil_con);
menu.setHeaderTitle("Option");
menu.add(Menu.NONE,EDIT,menu.NONE,"Edit Option");
menu.add(Menu.NONE,DELETE,menu.NONE,"Delete Option");
}
public boolean onContextItemSelected(MenuItem item){
switch (item.getItemId()){
case EDIT:
dbHandler.updateContact(Contacts.get(longClickItemIndex));
contactAdapter.notifyDataSetChanged();
break;
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickItemIndex));
Contacts.remove(longClickItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean contactExists(Contact contact){
String name = contact.getCar();
int countactCount = Contacts.size();
for (int i = 0; i < countactCount; i++)
{
if (name.compareToIgnoreCase(Contacts.get(i).getCar()) == 0)
return true;
}
return false;
}
public void onActivityResult(int reqcode, int rescode, Intent data){
if(rescode == RESULT_OK){
if(reqcode == 1){
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
}
private void populateList() {
contactAdapter = new ContactListAdapter();
contactListView.setAdapter(contactAdapter);
}
class ContactListAdapter extends ArrayAdapter<Contact> {
public ContactListAdapter() {
super(LoginActivity.this, R.layout.listview_item, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Contact currentContact = Contacts.get(position);
TextView car = (TextView) view.findViewById(R.id.contactname);
car.setText(currentContact.getCar());
TextView status = (TextView) view.findViewById(R.id.status);
status.setText(currentContact.getStatus());
ImageView img = (ImageView) view.findViewById(R.id.img);
img.setImageURI(currentContact.getimageURI());
return view;
}
}
}
it give this error on logcat
09-06 05:05:16.954
4910-4910/com.example.ahmed.vehiclepermitapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ahmed.vehiclepermitapp.LoginActivity$1.onClick(LoginActivity.java:85)
at android.view.View.performClick(View.java:4106)
at android.view.View$PerformClick.run(View.java:17052)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5059)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Hi i'm new to android and doing custom listview with checkbox, in that i'm facing random selection of another list item checkbox while scrolling. I have gone through some threads but didn't solve my problem. Pls help me out from this. Here is my custom adapter
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ViewRecord extends Activity {
DataBaseHelper db;
ListView listView;
Button delAll, more, setTime;
ListAdapter list;
CheckBox check;
boolean checks = false;
ArrayList<Contacts> arrayContacts = new ArrayList<Contacts>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.records);
listView = (ListView) findViewById(R.id.listview);
delAll = (Button) findViewById(R.id.delete);
more = (Button) findViewById(R.id.addMore);
setTime = (Button) findViewById(R.id.btnTime);
check = (CheckBox) findViewById(R.id.checkBox1);
loadlist();
// For adding more contacts to BlockList
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(ViewRecord.this, ContactList.class);
startActivity(intent);
}
});
// For selecting the whole Records to delete.....
check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list = new ListAdapter(getBaseContext());
checks = !checks;
for (int count =0; count<arrayContacts.size(); count++){
listView.setAdapter(list);
list.mCheckStates.put(count, checks);
list.notifyDataSetChanged();
}
// check.toggle();
}
});
}
private void loadlist() {
// TODO Auto-generated method stub
list = new ListAdapter(this);
listView.setAdapter(list);
//listView.setOnItemClickListener(this);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
arrayContacts.clear();
// Reading DataBase Contacts.
db = new DataBaseHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<Contacts> arrayStor = db.getContacts();
for (int i = 0; i < arrayStor.size(); i++) {
String Id = arrayStor.get(i).getContactId();
String Name = arrayStor.get(i).getContactName();
String Number = arrayStor.get(i).getContactNumber();
Contacts contacts = new Contacts();
contacts.setContactId(Id);
contacts.setContactName(Name);
contacts.setContactNumber(Number);
arrayContacts.add(contacts);
}
// listView.setAdapter(new ListAdapter(this));
db.close();
}
private class ListAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater inflater;
ViewHolder viewHolder;
CheckBox cb;
public ListAdapter(Context context) {
mCheckStates = new SparseBooleanArray(arrayContacts.size());
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayContacts.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
cb = (CheckBox) convertView.findViewById(R.id.checkox);
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
viewHolder = new ViewHolder();
viewHolder.txtName = (TextView) convertView.findViewById(R.id.txtdisplaypname);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txtName.setText(arrayContacts.get(position).getContactName().trim());
delAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alertbox = new AlertDialog.Builder(
ViewRecord.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
if(check.isChecked()==true){
db.emptyRecords();
check.toggle();
ViewRecord.this.onResume();
}else
{
for(int i = 0; i < arrayContacts.size(); i++){
{
if(mCheckStates.get(i)==true)
{
db.RemoveRecord(arrayContacts.get(i).getContactId().trim(), "", "");
System.out.println("The contact name and id is :" + arrayContacts.get(i).getContactId() + arrayContacts.get(i).getContactName());
ViewRecord.this.onResume();
}
}
}
Toast.makeText(getApplicationContext()," Records Deleted...",Toast.LENGTH_SHORT).show();
db.close();
}
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
db.close();
}
});
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<String> contactName = new ArrayList<String>();
ArrayList<String> contactNumber = new ArrayList<String>();
for(int i = 0; i < arrayContacts.size(); i++)
{
if(mCheckStates.get(i)==true)
{
// For sending contact names to schedule
contactName.add(arrayContacts.get(i).getContactName());
contactNumber.add(arrayContacts.get(i).getContactNumber()) ;
}
}
Intent sendIntent = new Intent (getApplicationContext(), Time_Settings.class);
sendIntent.putExtra("contactName", contactName);
sendIntent.putExtra("contactNumber", contactNumber);
// Toast.makeText(getApplicationContext(), contactName + contactNumber, 0).show();
startActivity(sendIntent);
}
});
return convertView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, checks);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
private class ViewHolder {
TextView txtName;
}
}
}
Here i did a view reusing thats why it does auto checking checkboxes, just remove the braces and else part from getView this solved my problem