unfortunately your app has stopped working when I click on button - runtime

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)

Related

Recyclerview Filter not working.its not searching the elements

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.

Parse.com Signup with a Profile Picture and cover from a drawable

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);

Can't stop javafx tables from ignoring my the setter function validation

I'm using javafx to do some table stuff. I want to validate my textfields in the myTextRow Class. In the "setText2" method I check the input if it is not bigger than 6 symbols, but it has no effects at all.
import java.util.ArrayList;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TextArea;
import javafx.util.Callback;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Supermain extends Application {
#Override
public void start(Stage primaryStage) {
ArrayList myindizes=new ArrayList();
final TableView<myTextRow> table = new TableView<>();
table.setEditable(true);
table.setStyle("-fx-text-wrap: true;");
//Table columns
TableColumn<myTextRow, String> clmID = new TableColumn<>("ID");
clmID.setMinWidth(160);
clmID.setCellValueFactory(new PropertyValueFactory<>("ID"));
TableColumn<myTextRow, String> clmtext = new TableColumn<>("Text");
clmtext.setMinWidth(160);
clmtext.setCellValueFactory(new PropertyValueFactory<>("text"));
clmtext.setCellFactory(new TextFieldCellFactory());
TableColumn<myTextRow, String> clmtext2 = new TableColumn<>("Text2");
clmtext2.setMinWidth(160);
clmtext2.setCellValueFactory(new PropertyValueFactory<>("text2"));
clmtext2.setCellFactory(new TextFieldCellFactory());
//Add data
final ObservableList<myTextRow> data = FXCollections.observableArrayList(
new myTextRow(5, "Lorem","bla"),
new myTextRow(2, "Ipsum","bla")
);
table.getColumns().addAll(clmID, clmtext,clmtext2);
table.setItems(data);
HBox hBox = new HBox();
hBox.setSpacing(5.0);
hBox.setPadding(new Insets(5, 5, 5, 5));
Button btn = new Button();
btn.setText("Get Data");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
for (myTextRow data1 : data) {
System.out.println("data:" + data1.getText2());
}
}
});
hBox.getChildren().add(btn);
BorderPane pane = new BorderPane();
pane.setTop(hBox);
pane.setCenter(table);
primaryStage.setScene(new Scene(pane, 640, 480));
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
public static class TextFieldCellFactory
implements Callback<TableColumn<myTextRow, String>, TableCell<myTextRow, String>> {
#Override
public TableCell<myTextRow, String> call(TableColumn<myTextRow, String> param) {
TextFieldCell textFieldCell = new TextFieldCell();
return textFieldCell;
}
public static class TextFieldCell extends TableCell<myTextRow, String> {
private TextArea textField;
private StringProperty boundToCurrently = null;
public TextFieldCell() {
textField = new TextArea();
textField.setWrapText(true);
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
this.setGraphic(textField);
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
// Show the Text Field
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
// myindizes.add(getIndex());
// Retrieve the actual String Property that should be bound to the TextField
// If the TextField is currently bound to a different StringProperty
// Unbind the old property and rebind to the new one
ObservableValue<String> ov = getTableColumn().getCellObservableValue(getIndex());
SimpleStringProperty sp = (SimpleStringProperty) ov;
if (this.boundToCurrently == null) {
this.boundToCurrently = sp;
this.textField.textProperty().bindBidirectional(sp);
} else if (this.boundToCurrently != sp) {
this.textField.textProperty().unbindBidirectional(this.boundToCurrently);
this.boundToCurrently = sp;
this.textField.textProperty().bindBidirectional(this.boundToCurrently);
}
double height = real_lines_height(textField.getText(), this.getWidth(), 30, 22);
textField.setPrefHeight(height);
textField.setMaxHeight(height);
textField.setMaxHeight(Double.MAX_VALUE);
// if height bigger than the biggest height in the row
//-> change all heights of the row(textfields ()typeof textarea) to this height
// else leave the height as it is
//System.out.println("item=" + item + " ObservableValue<String>=" + ov.getValue());
//this.textField.setText(item); // No longer need this!!!
} else {
this.setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
}
public class myTextRow {
private final SimpleIntegerProperty ID;
private final SimpleStringProperty text;
private final SimpleStringProperty text2;
public myTextRow(int ID, String text,String text2) {
this.ID = new SimpleIntegerProperty(ID);
this.text = new SimpleStringProperty(text);
this.text2 = new SimpleStringProperty(text2);
}
public void setID(int id) {
this.ID.set(id);
}
public void setText(String text) {
this.text.set(text);
}
public void setText2(String text) {
if(text2check(text)){
this.text2.set(text);}
else
{System.out.println("wrong value!!!");}
}
public int getID() {
return ID.get();
}
public String getText() {
return text.get();
}
public StringProperty textProperty() {
return text;
}
public String getText2() {
return text2.get();
}
public StringProperty text2Property() {
return text2;
}
public IntegerProperty IDProperty() {
return ID;
}
public boolean text2check(String t)
{
if(t.length()>6)return false;
return true;
}
}
private static double real_lines_height(String s, double width, double heightCorrector, double widthCorrector) {
HBox h = new HBox();
Label l = new Label("Text");
h.getChildren().add(l);
Scene sc = new Scene(h);
l.applyCss();
double line_height = l.prefHeight(-1);
int new_lines = s.replaceAll("[^\r\n|\r|\n]", "").length();
// System.out.println("new lines= "+new_lines);
String[] lines = s.split("\r\n|\r|\n");
// System.out.println("line count func= "+ lines.length);
int count = 0;
//double rest=0;
for (int i = 0; i < lines.length; i++) {
double text_width = get_text_width(lines[i]);
double plus_lines = Math.ceil(text_width / (width - widthCorrector));
if (plus_lines > 1) {
count += plus_lines;
//rest+= (text_width / (width-widthCorrector)) - plus_lines;
} else {
count += 1;
}
}
//count+=(int) Math.ceil(rest);
count += new_lines - lines.length;
return count * line_height + heightCorrector;
}
private static double get_text_width(String s) {
HBox h = new HBox();
Label l = new Label(s);
l.setWrapText(false);
h.getChildren().add(l);
Scene sc = new Scene(h);
l.applyCss();
// System.out.println("dubbyloop.FXMLDocumentController.get_text_width(): "+l.prefWidth(-1));
return l.prefWidth(-1);
}
}
A rule of the JavaFX Properties pattern is that for a property x, invoking xProperty().setValue(value) should always be identical to invoking setX(value). Your validation makes this not true. The binding your cell implementation uses invokes the setValue method on the property, which is why it bypasses your validation check.
(Side note: in all the code I am going to change the names so that they adhere to proper naming conventions.)
The default way to implement a property in this pattern is:
public class MyTextRow {
private final StringProperty text = new SimpleStringProperty();
public StringProperty textProperty() {
return text ;
}
public final void setText(String text) {
textProperty().set(text);
}
public final String getText() {
return textProperty().get();
}
}
By having the set/get methods delegate to the appropriate property methods, you are guaranteed these rules are enforced, even if the textProperty() methods is overridden in a subclass. Making the set and get methods final ensures that the rule is not broken by a subclass overriding those methods.
One approach might be to override the set and setValue methods in the property, as follows:
public class MyTextRow {
private final StringProperty text2 = new StringPropertyBase() {
#Override
public String getName() {
return "text2";
}
#Override
public Object getBean() {
return MyTextRow.this ;
}
#Override
public void setValue(String value) {
if (text2Check(value)) {
super.setValue(value);
}
}
#Override
public void set(String value) {
if (text2Check(value)) {
super.set(value);
}
}
}
public StringProperty text2Property() {
return text2 ;
}
public final void setText2(String text2) {
text2Property().set(text2);
}
public final String getText2() {
return text2Property().get();
}
// ...
}
however, I think this will break the bidirectional binding that you have with the text property in the TextArea (basically, there is no way to communicate back to the text area when a change is vetoed, so the text area will not know to revert to the previous value). One fix would be to implement your cell using listeners on the properties instead of bindings. You could use a TextFormatter on the text area that simply updates the property and vetoes the text change if the change doesn't occur.
Here is a complete SSCCE using this approach:
import java.util.function.Function;
import java.util.function.UnaryOperator;
import javafx.application.Application;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.property.StringPropertyBase;
import javafx.scene.Scene;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
import javafx.stage.Stage;
public class VetoStringChange extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Item> table = new TableView<>();
table.setEditable(true);
table.getColumns().add(column("Item", Item::nameProperty));
table.getColumns().add(column("Description", Item::descriptionProperty));
for (int i = 1; i <= 20 ; i++) {
table.getItems().add(new Item("Item "+i, ""));
}
primaryStage.setScene(new Scene(table, 600, 600));
primaryStage.show();
}
public static <S> TableColumn<S,String> column(String title, Function<S,Property<String>> property) {
TableColumn<S,String> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
col.setCellFactory(tc -> new TextAreaCell<S>(property));
col.setPrefWidth(200);
return col ;
}
public static class TextAreaCell<S> extends TableCell<S, String> {
private TextArea textArea ;
public TextAreaCell(Function<S, Property<String>> propertyAccessor) {
textArea = new TextArea();
textArea.setWrapText(true);
textArea.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textArea.setMaxHeight(Double.MAX_VALUE);
UnaryOperator<Change> filter = c -> {
String proposedText = c.getControlNewText() ;
Property<String> prop = propertyAccessor.apply(getTableView().getItems().get(getIndex()));
prop.setValue(proposedText);
if (prop.getValue().equals(proposedText)) {
return c ;
} else {
return null ;
}
};
textArea.setTextFormatter(new TextFormatter<String>(filter));
this.setGraphic(textArea);
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
if (! textArea.getText().equals(item)) {
textArea.setText(item);
}
// Show the Text Field
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
this.setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
public static class Item {
private final StringProperty name = new StringPropertyBase() {
#Override
public Object getBean() {
return Item.this;
}
#Override
public String getName() {
return "name" ;
}
#Override
public void set(String value) {
if (checkValue(value)) {
super.set(value);
}
}
#Override
public void setValue(String value) {
if (checkValue(value)) {
super.setValue(value);
}
}
};
private final StringProperty description = new SimpleStringProperty();
public Item(String name, String description) {
setName(name);
setDescription(description);
}
private boolean checkValue(String value) {
return value.length() <= 6 ;
}
public final StringProperty nameProperty() {
return this.name;
}
public final String getName() {
return this.nameProperty().get();
}
public final void setName(final String name) {
this.nameProperty().set(name);
}
public final StringProperty descriptionProperty() {
return this.description;
}
public final String getDescription() {
return this.descriptionProperty().get();
}
public final void setDescription(final String description) {
this.descriptionProperty().set(description);
}
}
public static void main(String[] args) {
launch(args);
}
}
Another approach is to allow a "commit and revert" type strategy on your property:
public class MyTextRow {
private final StringProperty text2 = new SimpleStringProperty();
public MyTextRow() {
text2.addListener((obs, oldText, newText) -> {
if (! checkText2(newText)) {
// sanity check:
if (checkText2(oldText)) {
text2.set(oldText);
}
}
});
}
public StringProperty text2Property() {
return text ;
}
public final void setText2(String text2) {
text2Property().set(text2);
}
public final String getText2() {
return text2Property().get();
}
}
In general I dislike validation by listening for an invalid value and reverting like this, because other listeners to the property will see all the changes, including changes to and from invalid values. However, this might be the best option in this case.
Finally, you could consider vetoing invalid changes as in the first option, and also setting a TextFormatter on the control in the cell that simply doesn't allow text entry that results in an invalid string. This isn't always possible from a usability perspective (e.g. if empty strings are invalid, you almost always want to allow the user to temporarily delete all the text), and it means keeping two validation checks in sync in your code, which is a pain.

Parse search a specific user

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());
}
}
});
}
}

How to fix checkboxes auto random selection by scrolling listview, and also shows java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10

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

Resources