issues Spotting the error - android-activity

The error that i'm getting is "Multiple markers at this line
- Syntax error, insert "}" to complete
ClassBody
- Syntax error, insert ";" to complete
Statement
- Syntax error, insert ")" to complete
Expression"
still on the same line i've tried placing different ")" and"}" and they just make it worse even tried playing around with removing or moving them around still same issue ..cannot run cause of the error
My SignUp class,
public class SignUp extends Activity {
private EditText reg_fullname, reg_username, reg_email, reg_password, reg_confirmpassword;
private Button btnRegister;
private LoginDataBaseAdapter dataBaseAdapter;
private TextView loginScreen;
protected DataBaseHelper DB = new DataBaseHelper(SignUp.this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
loginScreen = (TextView) this.findViewById(R.id.link_to_login);
//Listening to Login Screen Link
btnRegister = (Button) findViewById(R.id.btnRegister);
loginScreen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.link_to_login:
startActivity(new Intent(SignUp.this, LoginScreen.class));
finish();
break;
case R.id.btnRegister:
// I think they have to be final to be used in the onClickListener
final String fullname = reg_fullname.getText().toString();
final String username = reg_username.getText().toString();
final String password = reg_password.getText().toString();
final String email = reg_email.getText().toString();
boolean invalid = false;
if(fullname.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Enter your Firstname", Toast.LENGTH_SHORT).show();
}
else
if(username.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Username", Toast.LENGTH_SHORT).show();
}
else
if(password.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Password", Toast.LENGTH_SHORT).show();
}
else
if(email.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Email ID", Toast.LENGTH_SHORT).show();
}
else
if(invalid == false)
{
addEntry(fullname, username, password, email);
Intent i_register = new Intent(SignUp.this, LoginScreen.class);
startActivity(i_register);
finish();
}
}
break;
} ****error appears here ***
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
dataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy SignUp- Error", e.getMessage());
}}
private void addEntry(String fullname, String username, String password, String email)
{
SQLiteDatabase db = DB.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("fullname", fullname);
values.put("username", username);
values.put("password", password);
values.put("email", email);
try
{
db.insert(DataBaseHelper.DATABASE_TABLE_NAME, null, values);
Toast.makeText(getApplicationContext(), "your details submitted Successfully...", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}}

You need the following symbols after your break;:
...
break;
}
});
}
#Override
protected void onDestroy() {

Related

following facebook login: setReadPermissions and registerCallback giving me error

trying to use FB login, followed their steps, but Android Studio gives me error: Cannot resolve methods .setReadPermissions and .registerCallback...
am new to this development and tech world... please, help! What am I doing wrong? Looked through many Q&A here, but none is giving me answers. Help much appreciated. Thanks!
I am trying to build a simple OCR app, with FB, Google logins and one independent register button. Code for registration class as follows:
public class Registration extends AppCompatActivity {
DatabaseHelper databaseHelper;
CallbackManager callbackManager;
GoogleSignInClient mGoogleSignInClient;
private static final String TAG = "AndroidClarified";
EditText et_username, et_password, et_cpassword, et_email;
RadioGroup radioSexGroup;
RadioButton radioSexButton;
Button btn_register, btnFBLogin, google_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
try {
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
AccessToken accessToken = AccessToken.getCurrentAccessToken();
Profile profile = Profile.getCurrentProfile();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
google_button = findViewById(R.id.google_button);
GoogleSignInOptions gso = new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getResources().getString(R.string.web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
et_username = findViewById(R.id.et_username);
et_password = findViewById(R.id.et_password);
et_cpassword = findViewById(R.id.et_cpassword);
et_email = findViewById(R.id.et_email);
radioSexGroup = findViewById(R.id.radioGroup);
final int selectedId = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = findViewById(selectedId);
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = et_username.getText().toString();
String password = et_password.getText().toString();
String confirm_password = et_cpassword.getText().toString();
String email = et_email.getText().toString();
if (username.equals("") || password.equals("") ||
confirm_password.equals("") || email.isEmpty()) {
Toast.makeText(getApplicationContext(), "Fields Required",
Toast.LENGTH_SHORT).show();
} else {
if (password.equals(confirm_password)) {
boolean checkUsername =
databaseHelper.CheckUsername(username);
if (checkUsername) {
boolean insert = databaseHelper.Insert(username,
password, email);
if (insert) {
Toast.makeText(getApplicationContext(),
"Registered", Toast.LENGTH_SHORT).show();
et_username.setText("");
et_password.setText("");
et_cpassword.setText("");
et_email.setText("");
}
if (!isValidEmail(et_email.getText().toString())) { Toast.makeText(getApplicationContext(), "Email is not valid", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Username already taken", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_SHORT).show();
}
}
}
}
private boolean isValidEmail(String email) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
});
callbackManager = CallbackManager.Factory.create();
btnFBLogin = findViewById(R.id.btnFBLogin);
List permissionNeeds = Arrays.asList("email", "user_birthday", "gender");
btnFBLogin.performClick();
btnFBLogin.setReadPermissions(permissionNeeds);
btnFBLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
if (AccessToken.getCurrentAccessToken() != null) {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if (json != null) {
String text = "<b>Name :</b> " + json.getString("name") + "<br><br><b>Email :</b> " + json.getString("email") + "<br><br><b>Profile link :</b> " + json.getString("link");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
#Override
public void onCancel() {
Log.d("fb_login_sdk", "callback cancel");
}
#Override
public void onError(FacebookException exception) {
Log.d("fb_login_sdk", "callback onError");
}
});
google_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, 101);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
switch (requestCode) {
case 101:
try {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
GoogleSignInAccount account = task.getResult(ApiException.class);
String idToken = account.getIdToken();
onLoggedIn(account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
}
break;
}
}
private void onLoggedIn(GoogleSignInAccount mGoogleSignInAccount) {
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra(ProfileActivity.GOOGLE_ACCOUNT, mGoogleSignInAccount);
startActivity(intent);
finish();
}
public void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (GoogleSignIn.getLastSignedInAccount(this) != null) {
Toast.makeText(this, "Already Logged In", Toast.LENGTH_SHORT).show();
onLoggedIn(account);
} else {
Log.d(TAG, "Not logged in");
}
}
}

Parse and Facebook SDK accessToken return null

I'm trying to extract information using the Facebook Graph Api along with Parse API. When calling the Graph API, The GraphRepsone is null. The problem is because the accessToken is null but I can't figure out how to fix after trying many different ways.
buttonSignUpWithFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// this is where you can begin doing facebook sign up process
Log.i(TAG, "did click on facebook button");
List<String> permissions = Arrays.asList("user_location", "user_friends", "email", "public_profile");
ParseFacebookUtils.logInWithReadPermissionsInBackground(SignUpActivity.this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("App", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("App", "User signed up and logged in through Facebook!");
startActivity(new Intent(SignUpActivity.this, Home.class));
} else {
Log.d("App", "User logged in through Facebook!");
setupUser();
startActivity(new Intent(SignUpActivity.this, Home.class));
}
}
public void setupUser() {
accessToken = AccessToken.getCurrentAccessToken();
}
});
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (response != null) {
try {
String email = object.getString("email");
String firstName = object.getString("first_name");
Log.d(TAG, "first name " + firstName);
} catch (JSONException e) {
e.printStackTrace();
}
// String firstName = jsonResponseObject.getFirstName();
// String lastName = jsonResponseObject.getLastName();
}
}
});
Bundle param = new Bundle();
param.putString("fields","cover, birthday, email, first_name, last_name, ");
request.setParameters(param);
request.executeAsync();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
I'd hate to give a vague answer, but I don't think the problem is in the code snippet. I suggest you revise your steps and make sure you followed these links completely again:
https://developers.facebook.com/docs/android/getting-started
https://parse.com/docs/android/guide#users-facebook-users

How to reopen/prevent closing of ControlsFX LoginDialog on failed login?

In my application, the first I do is request the user to login using the controlsFX LoginDialog. If the login is successful, I display the application, however if it fails the login window will close.
I would rather the login window stay open to allow the user to attempt to login again.
public void start(Stage stage) throws Exception {
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String,String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if(success){
openDriverWindow(stage);
}else {
//Display error message
}
return null;
}
});
ld.show();
}
If the login is unsuccessful, the dialog closes - which requires the user to reopen the application.
You can use Dialog from JDK8u40 which will be released at march 2015 or use dialogs from ConrolsFX (openjfx-dialogs-1.0.2). There is a code to implement Dialog which will not be closed until authentication is not passed.
// Create the custom dialog.
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("Login Dialog");
dialog.setHeaderText("Look, a Custom Login Dialog");
dialog.setGraphic(new ImageView(this.getClass().getResource("login.png").toString()));
// Set the button types.
ButtonType loginButtonType = new ButtonType("Login", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField username = new TextField();
username.setPromptText("Username");
PasswordField password = new PasswordField();
password.setPromptText("Password");
grid.add(new Label("Username:"), 0, 0);
grid.add(username, 1, 0);
grid.add(new Label("Password:"), 0, 1);
grid.add(password, 1, 1);
// Enable/Disable login button depending on whether a username was entered.
Button loginButton = (Button)dialog.getDialogPane().lookupButton(loginButtonType);
loginButton.setDisable(true);
**// Prevent closing dialog if not authenticated**
loginButton.addEventFilter(ActionEvent.ACTION, (event) -> {
if (!authenticated()) {
event.consume();
}
});
// Do some validation (using the Java 8 lambda syntax).
username.textProperty().addListener((observable, oldValue, newValue) -> {
loginButton.setDisable(newValue.trim().isEmpty());
});
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
Platform.runLater(() -> username.requestFocus());
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return new Pair<>(username.getText(), password.getText());
}
return null;
});
Optional<Pair<String, String>> result = dialog.showAndWait();
result.ifPresent(usernamePassword -> {
System.out.println("Username=" + usernamePassword.getKey() + ", Password=" + usernamePassword.getValue());
});
this example was given from this article where you can find many useful examples
Try this:
public class Main extends Application{
private boolean login(String key, String value){
Pair loginData = new Pair<String, String>("test", "test");
if (loginData.getKey().equals(key) && loginData.getValue().equals(value)) {
return true;
}
else {
//Вывести Alert.
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
Alert alert = new Alert(Alert.AlertType.ERROR, "Вы ввели неправильное имя или пароль");
alert.setTitle("Error");
alert.showAndWait();
} catch (Exception e) {
e.printStackTrace();
}
}
});
return false;
}
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Terminal Kuban-electro");
getLogin(primaryStage);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
System.exit(0);
}
});
}
private void getLogin(Stage primaryStage){
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String, String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if (success) {
Scene scene = null;
try {
scene = new Scene(FXMLLoader.load(getClass().getClassLoader().getResource("fxml/main.fxml")));
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
}
} else {
getLogin(primaryStage);
}
return null;
}
});
ld.setHeaderText("Введите имя пользователя и пароль");
ld.setTitle("Авторизация");
ld.show();
}
public static void main(String[] args) throws MalformedURLException {
//Инициализация формы в потоке
Thread myThready = new Thread(() -> {
launch(args);
});
myThready.start();
}
}

I am working with facebook game request

I finished working with sending the request with android reading https://developers.facebook.com/docs/howtos/androidsdk/3.0/send-requests/
but i'm having a problem with handling requests.
https://developers.facebook.com/docs/howtos/androidsdk/3.0/app-link-requests/
I think I did what it told me to do, but I can't get the uri and the requestid
they are all null.
I thing the problem is that when I receive a request I can't click the accept button.
It says that the playstore can't find the app. So the request doesn't disappear.
How can I solve the problem?
public class MainActivity extends Activity {
private static final List<String> PERMISSIONS = Arrays
.asList("read_requests");
private Bundle SIS;
private Session.StatusCallback logincallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
if (session.isOpened()) {
updateview();
getp();
loginlogoutbutton.setText("Login");
onSessionStateChange(session, state, exception);
} else {
}
}
};
public void updateview() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
tt.setText(user.getId());
}
}
});
} else
{
tt.setText("Login");
}
}
private Button loginlogoutbutton;
private Button sendrequestbutton;
private Button testbtn;
private TextView tt;
private String app_id = "APP ID";
private String requestId;
public void getp() {
Session session = Session.getActiveSession();
if (session == null || !session.isOpened()) {
return;
}
List<String> permissions = session.getPermissions();
if (!permissions.containsAll(PERMISSIONS)) {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS)
.setCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
}
}));
} else {
}
}
#Override
public void onResume() {
super.onResume();
checkforrequest();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SIS = savedInstanceState;
tt = (TextView) findViewById(R.id.tex);
loginlogoutbutton = (Button) findViewById(R.id.loginlogoutbtn);
loginlogoutbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
onClickLoginLogout();
}
});
sendrequestbutton = (Button) findViewById(R.id.sendrequest);
sendrequestbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
sendRequestDialog();
}
});
testbtn = (Button) findViewById(R.id.button1);
testbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
checkforrequest();
}
});
ConfirmLogin(app_id);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
public boolean ConfirmLogin(String iappid) {
app_id = iappid;
Session session = Session.getActiveSession();
boolean dd = true;
if (session == null) {
if (SIS != null) {
session = Session.restoreSession(this, null,
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
// TODO Auto-generated method stub
}
}, SIS);
}
if (session == null) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
dd = true;
} else {
dd = false;
}
}
return dd;
}
public void onClickLoginLogout() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else if (session.isClosed()) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
Session.setActiveSession(session);
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else {
session.closeAndClearTokenInformation();
loginlogoutbutton.setText("Login");
}
}
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message",
"Learn how to make your Android apps social");
params.putString("data", "{\"badge_of_awesomeness\":\"1\","
+ "\"social_karma\":\"5\"}");
WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(this,
Session.getActiveSession(), params)).setOnCompleteListener(
new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
} else {
}
} else {
final String requestId = values
.getString("request");
if (requestId != null) {
maketoast(requestId);
} else {
}
}
}
}).build();
requestsDialog.show();
}
public void checkforrequest() {
maketoast("0");
Uri intentUri = this.getIntent().getData();
if (intentUri != null) {
String requestIdParam = intentUri.getQueryParameter("request_ids");
maketoast("1 : " +requestIdParam);
if (requestIdParam != null) {
String array[] = requestIdParam.split(",");
requestId = array[0];
}
}
else
{
maketoast("uri = null");
}
}
public void maketoast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void getRequestData(final String inRequestId) {
// Create a new request for an HTTP GET with the
// request ID as the Graph path.
maketoast("2");
Request request = new Request(Session.getActiveSession(), inRequestId,
null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Process the returned response
GraphObject graphObject = response.getGraphObject();
FacebookRequestError error = response.getError();
// Default message
String message = "Incoming request";
if (graphObject != null) {
// Check if there is extra data
if (graphObject.getProperty("data") != null) {
try {
// Get the data, parse info to get the
// key/value info
JSONObject dataObject = new JSONObject(
(String) graphObject
.getProperty("data"));
// Get the value for the key -
// badge_of_awesomeness
String badge = dataObject
.getString("badge_of_awesomeness");
// Get the value for the key - social_karma
String karma = dataObject
.getString("social_karma");
// Get the sender's name
JSONObject fromObject = (JSONObject) graphObject
.getProperty("from");
String sender = fromObject
.getString("name");
String title = sender + " sent you a gift";
// Create the text for the alert based on
// the sender
// and the data
message = title + "\n\n" + "Badge: "
+ badge + " Karma: " + karma;
} catch (JSONException e) {
message = "Error getting request info";
}
} else if (error != null) {
message = "Error getting request info";
}
}
maketoast(message);
}
});
// Execute the request asynchronously.
Request.executeBatchAsync(request);
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
// Check if the user is authenticated and
// an incoming notification needs handling
if (state.isOpened() && requestId != null) {
maketoast("3");
getRequestData(requestId);
requestId = null;
} else if (requestId == null) {
maketoast("4");
}
if (state.isOpened()) {
} else if (state.isClosed()) {
}
}
}
this is the code.

My custome list view not update with new data

Hello I created a custom list view and for update used notifyDataSetChanged() method but my list not updated. please help me.
this is my source code
public class fourthPage extends ListActivity {
ListingFeedParser ls;
List<Listings> data;
EditText SearchText;
Button Search;
private LayoutInflater mInflater;
private ProgressDialog progDialog;
private int pageCount = 0;
String URL;
ListViewListingsAdapter adapter;
Message msg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle b = getIntent().getExtras();
URL = b.getString("URL");
Log.i("Ran->URL", "->" + URL);
MYCITY_STATIC_DATA.fourthPage_main_URL = URL;
final ListingFeedParser lf = new ListingFeedParser(URL);
Search = (Button) findViewById(R.id.searchButton);
SearchText = (EditText) findViewById(R.id.search);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(SearchText.getWindowToken(), 0);
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {
progDialog = ProgressDialog.show(this, "",
"Loading please wait....", true);
progDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
data = lf.parse();
} catch (Exception e) {
e.printStackTrace();
}
msg = new Message();
msg.what = 1;
fourthPage.this._handle.sendMessage(msg);
}
}).start();
Search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SearchText = (EditText) findViewById(R.id.search);
if (SearchText.getText().toString().equals(""))
return;
CurrentLocationTimer myLocation = new CurrentLocationTimer();
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(final Location location) {
Toast.makeText(
getApplicationContext(),
location.getLatitude() + " "
+ location.getLongitude(),
Toast.LENGTH_LONG).show();
String URL = "http://75.125.237.76/phone_feed_2_point_0_test.php?"
+ "lat="
+ location.getLatitude()
+ "&lng="
+ location.getLongitude()
+ "&page=0&search="
+ SearchText.getText().toString();
Log.e("fourthPage.java Search URL :->", "" + URL);
Bundle b = new Bundle();
b.putString("URL", URL);
Intent it = new Intent(getApplicationContext(),
fourthPage.class);
it.putExtras(b);
startActivity(it);
}
};
myLocation.getLocation(getApplicationContext(),
locationResult);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"No data available for this request", Toast.LENGTH_LONG)
.show();
}
}
private Handler _handle = new Handler() {
#Override
public void handleMessage(Message msg) {
progDialog.dismiss();
if (msg.what == 1) {
if (data.size() == 0 || data == null) {
Toast.makeText(getApplicationContext(),
"No data available for this request",
Toast.LENGTH_LONG).show();
}
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
adapter = new ListViewListingsAdapter(getApplicationContext(),
R.layout.list1, R.id.title, data, mInflater);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(),
"Error in retrieving the method", Toast.LENGTH_SHORT)
.show();
}
}
};
public void onListItemClick(ListView parent, View v, int position, long id) {
// remember i m going from bookmark list
MYCITY_STATIC_DATA.come_from_bookmark = false;
Log.i("4thPage.java - MYCITY_STATIC_DATA.come_from_bookmark",
"set false - > check" + MYCITY_STATIC_DATA.come_from_bookmark);
Listings sc = (Listings) this.getListAdapter().getItem(position);
if (sc.getName().equalsIgnoreCase("SEE MORE...")) {
pageCount = pageCount + 1;
final ListingFeedParser lf = new ListingFeedParser((URL.substring(
0, URL.length() - 1)) + pageCount);
try {
progDialog = ProgressDialog.show(this, "",
"Loading please wait....", true);
progDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
data.remove(data.size() - 1);
data.addAll(lf.parse());
Message msg = new Message();
msg.what = 1;
fourthPage.this._handle.sendMessage(msg);
}
}).start();
} catch (Exception e) {
pageCount = pageCount - 1;
// TODO: handle exception
Toast newToast = Toast.makeText(this, "Error in getting Data",
Toast.LENGTH_SHORT);
}
} else {
Bundle b = new Bundle();
b.putParcelable("listing", sc);
Intent it = new Intent(getApplicationContext(),
FifthPageTabbed.class);
it.putExtras(b);
startActivity(it);
}
}
#Override
public void onBackPressed() {
setResult(0);
finish();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.e("RESUME:-)", "4th Page onResume");
try {
//adapter.notifyDataSetChanged();
//setListAdapter(adapter);
//getListView().setTextFilterEnabled(true);
} catch (Exception e) {
Log.e("EXCEPTION in 4th page",
"in onResume msg:->" + e.getMessage());
}
}
}
Do not re-create the object of ArrayList or Array you are passing to adapter, just modify same ArrayList or Array again. and also when array or arrylist size not changed after you modify adapter then in that case notifydatasetchange will not work.
In shot it is work only when array or arraylist size increases or decreases.
What version of Android are you targeting? The latest version seems to have revised how notifyDataSetChanged() works. If you target sdk 11 it might work?
Also, there seems to be a different (and very thorough answer) to this question in another post:
notifyDataSetChanged example