I have an android app in which there are many scenarios where request and response happens to-from server. For example:login i.e. authentication. When user enters username and password, then the credentials are verified against the one responded by Server.
But sometimes what happens is that due to slow network the response comes late and android pop-up a force close dialog box, which is highly embarrassing.
I was thinking that is there a way to segregate the code which hits the server in some separate thread and till it gets me a response. I may show a progress bar instead of force close. Is it a good solution?
Example code:
//this code will be called when user presses Login button on UI
public void authenticate(View view) {
//the logic for authentication
if(authentication==true){
//go to home page
}
}
In the above code how can I separate the logic for authentication so that force close does not occur when response is late as expected.
I would also appreciate any other better approach to tackle such scenarios of force close.
Do not include any task which takes time to execute in your main thread. You should do httpCommunication in different thread. and it will avoid this ANR.
What docs says >>
In Android, application responsiveness is monitored by the Activity Manager and Window Manager system services. Android will display the ANR dialog for a particular application when it detects one of the following conditions:
No response to an input event (e.g. key press, screen touch) within 5 seconds
A BroadcastReceiver hasn't finished executing within 10 seconds
Read this document specially created for Designing for responsiveness and to avoid ANR
You can use AsyncTask as well.
You can either use AsyncTask or http://loopj.com/android-async-http/
Show a progress dialog on UI meanwhile. Provide a callback function which will be called once response from server is received.
Use below sample code to do a login process. You can use AsyncTask to do the login process.
The LoginActivity class, which uses AsyncTask.
On Login button click, I am executing the AsyncTask.
During the login process, this will display a ProgressDialog
After the process completion, dismisses the ProgressDialogand displays a status message to user
The class code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private Button login_Button = null;
private EditText userNameText = null;
private EditText passwordText = null;
private String uName = "";
private String pass = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_login);
login_Button = (Button) findViewById(R.id.cmdDoLogin);
userNameText = (EditText) findViewById(R.id.editTextUserName);
passwordText = (EditText) findViewById(R.id.editTextPassword);
login_Button.setOnClickListener(new OnClickListener() {
public void onClick(View paramView) {
uName = userNameText.getText().toString().trim();
pass = passwordText.getText().toString().trim();
if (uName.equals("") || pass.equals("")) {
Toast.makeText(LoginActivity.this,
"Fill both username and password fields",
Toast.LENGTH_SHORT).show();
} else {
new LoginActivity.DoLoginProcess().execute(); // calling the AsyncTask here
}
}
});
}
private class DoLoginProcess extends AsyncTask<Void, Void, Integer> {
ProgressDialog pd = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(LoginActivity.this);
pd.setTitle("Logging In...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
int loginStatus = 0 ; // treat this as loginStatus. 0 = login failed; 1=login success. You can return this value to onPostExecute function
//*********************************************
// do login process over internet here. Hope you already have the code to do the login process over internet.
//*********************************************
return loginStatus;
}
#Override
protected void onPostExecute(Integer status) {
super.onPostExecute(status);
pd.dismiss(); // dismiss the progress dialog
if (status == 0) { // login failed
AlertDialog alertDialog = new AlertDialog.Builder(
LoginActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Login failed");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
LoginActivity.this.finish();
dialog.cancel();
}
});
alertDialog.setIcon(android.R.drawable.ic_dialog_info);
alertDialog.show();
} else if(status == 1) { // login success
AlertDialog alertDialog = new AlertDialog.Builder(
LoginActivity.this).create();
alertDialog.setTitle("Success");
alertDialog.setMessage("Login success");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
LoginActivity.this.finish();
dialog.cancel();
}
});
alertDialog.setIcon(android.R.drawable.ic_dialog_info);
alertDialog.show();
}
}
}
}
The test_login layout XMl file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/loginbglayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp" >
<TableLayout
android:id="#+id/holderLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<TableRow
android:id="#+id/row1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<TextView
android:id="#+id/textViewUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="right"
android:text="UserName"
android:textColor="#ffffff" />
<EditText
android:id="#+id/editTextUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/row2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="right"
android:text="Password"
android:textColor="#ffffff" />
<EditText
android:id="#+id/editTextPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="textPassword" />
</TableRow>
<TableRow
android:id="#+id/row3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center" >
<View
android:layout_width="0dp"
android:layout_height="2dip"
android:layout_weight="1"
android:focusable="false" />
<Button
android:id="#+id/cmdDoLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Login" >
</Button>
</TableRow>
</TableLayout>
</RelativeLayout>
Related
As the title says, I have encountered that error when I tried working with Firebase database. I have tried numerous solutions found online but nothing seems to have worked for me. Below you can find my code and also, a brief information regarding on what I've tried so far before posting on stackOverflow.
The code is the following:
package com.example.vlad.restaurantorder;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.vlad.restaurantorder.Model.User;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rengwuxian.materialedittext.MaterialEditText;
public class LogIn extends AppCompatActivity {
EditText editPhone, editPassword;
Button btnLogIn;
FirebaseDatabase database;
DatabaseReference tableUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
btnLogIn = (Button)findViewById(R.id.btnLogInScreenLogIn);
editPhone = (MaterialEditText)findViewById(R.id.edtPhone);
editPassword = (MaterialEditText)findViewById(R.id.edtPassword);
//database
database = FirebaseDatabase.getInstance();
tableUser = database.getReference("User");
btnLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog progressDialog = new ProgressDialog(LogIn.this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
tableUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(editPhone.getText().toString()).exists()){
progressDialog.dismiss();
User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
if(user.getPassword().equals(editPassword.getText().toString())){
Toast.makeText(getApplicationContext(), "You are logged in!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Log in failed!", Toast.LENGTH_SHORT).show();
}
}
else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "User does not exists!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
}
What I have tried so far before posting here: Disabling proGuard and putting minifyEnable on false in build.gradle in debug{}; Restarting android studio, as I've read other people's posts who also encountered the problem said that this worked for them; On line where I used tableUser = database.getReference("User"); I also tried using tableUser = database.getReference().child("User");
Any help is much appreciated. Thank you very much
Later edit: adding the LogIn activity xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/login_screen_image"
tools:context="com.example.vlad.restaurantorder.LogIn">
<LinearLayout
android:orientation="vertical"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtPhone"
android:hint="Phone Number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#android:color/white"
android:text="0293292442"
android:textColor="#android:color/white"
android:textSize="34sp"
android:inputType="phone"
app:met_floatingLabel="highlight"
app:met_baseColor="#android:color/white"
app:met_maxCharacters="11"
app:met_primaryColor="#android:color/white"
app:met_singleLineEllipsis="true"
/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtPassword"
android:hint="Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#android:color/white"
android:text="5678"
android:textColor="#android:color/white"
android:textSize="34sp"
android:inputType="textPassword"
app:met_floatingLabel="highlight"
app:met_baseColor="#android:color/white"
app:met_maxCharacters="11"
app:met_primaryColor="#android:color/white"
app:met_singleLineEllipsis="true"
/>
</LinearLayout>
<info.hoang8f.widget.FButton
android:id="#+id/btnLogInScreenLogIn"
android:text="#string/LogIn"
android:textColor="#android:color/white"
android:layout_marginRight="8dp"
android:layout_marginLeft="8dp"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:buttonColor="#color/btnLogIn"
app:shadowColor="#android:color/black"
app:shadowEnabled="true"
app:shadowHeight="5dp"
app:cornerRadius="4dp"
/>
Later edit: LogCat image:
It seems your code should work just fine if there is no other warning/error showing up. The missing instance error/message might only be because it takes some time to read the data from Firebase.
After adding the ValueEventListener, the app will take some time to "listen" to or read the data from Firebase. So, add some log messages to each of the if/else block as below, recompile and fire up the app, open the Logcat view in Android Studio and then click the button btnLogIn on the app screen. Then wait (make sure internet is available to the device/emulator and Firebase Database is connected).
In Logcat window, you should see the Log messages show up depending on the if/else block that was entered in onDataChange. E.g..... D/ANY_TAG: entered onDataChange
Code with debug lines:
tableUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("ANY_TAG", "entered onDataChange");
if(dataSnapshot.child(editPhone.getText().toString()).exists()){
Log.d("ANY_TAG", "entered onDataChange/childExists");
progressDialog.dismiss();
User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
if(user.getPassword().equals(editPassword.getText().toString())){
Log.d("ANY_TAG", "entered onDataChange/childExists/equalPassword");
Toast.makeText(getApplicationContext(), "You are logged in!", Toast.LENGTH_SHORT).show();
}
else{
Log.d("ANY_TAG", "entered onDataChange/childExists/unEqualPasswords");
Toast.makeText(getApplicationContext(), "Log in failed!", Toast.LENGTH_SHORT).show();
}
}
else {
Log.d("ANY_TAG", "entered onDataChange/childDoesNotExist");
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "User does not exists!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I have two rather basic questions I believe which needs answering:
1) When I run my emulator on the home screen my SignIn button is unresponsive and I am unsure why as I have tried alternative methods but whenever I click nothing happens and no error is showing. Code is shown below:
package com.techblogon.loginexample;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class HomeActivity extends Activity
{
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
// Method to handleClick Event of Sign In Button
public void signIn(View V)
{
final Dialog dialog = new Dialog(HomeActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIN);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(HomeActivity.this, "Welcome", Toast.LENGTH_LONG).show();
dialog.dismiss();
Intent ii=new Intent(HomeActivity.this,MainMenu.class);
startActivity(ii);
}
else
{
Toast.makeText(HomeActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Could somebody provide me with the best sqlite database viewer for eclipse, I am looking to view the records of the database I have created on my emulator
My XML is as follows
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/picture" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello, Welcome"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/buttonSignIN"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:text="Sign In" />
<Button
android:id="#+id/buttonSignUP"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:text="Sign Up" />
</LinearLayout>
you are missing an attribute in xml for buttonSignIN button
android:onClick="signIn"
Try this,
<Button
android:id="#+id/buttonSignIN"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:onClick="signIn"
android:text="Sign In" />
You need to understand the difference between setting clickListener in java code and setting a attribute from xml for the button click. These are two different ways in which you could achieve click events for any element.
I have a strange problem here with an EditText view. In onPause() after an orientation change, the EditText view returns text via getText() that was never assigned to it.
In fact, the EditText object in question is only assigned an empty string.
In the error situation, it returns part(!) of a text that was assigned to a different TextView.
This does however not happen if onPause is triggered by pressing the "back" key.
Can anybody give me a clue? I do not understand what is happening here:
My activity:
package com.example.rotationtest;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private final String LOG_TAG = "Test";
private EditText mEditText;
private TextView mTextView;
private EditOk mEditOk;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.title);
mEditText = (EditText) findViewById(R.id.editText);
mEditText.setText("");
mEditOk = new EditOk() {
#Override
public void ok(String result) {
mTextView.setText(result);
}
};
editTextDialog(R.string.dialog_title, (CharSequence)getString(R.string.dialog_title), mTextView.getText().toString(), mEditOk);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
abstract class EditOk {
abstract public void ok(String result);
}
void editTextDialog(int titleId, CharSequence message, String text,
final EditOk ok) {
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.edittext_dialog,
(ViewGroup) findViewById(R.id.layout_root));
TextView messageView = (TextView) layout.findViewById(R.id.text);
messageView.setText(message);
final EditText input = (EditText) layout.findViewById(R.id.editTextDialog);
Log.d(LOG_TAG, "input = " + input);
input.setTransformationMethod(android.text.method.SingleLineTransformationMethod.getInstance());
input.setText(text);
new AlertDialog.Builder(this)
.setTitle(titleId)
.setView(layout)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String newName = input.getText().toString();
if (newName.length() != 0) {
ok.ok(newName);
}
}})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setResult(RESULT_CANCELED);
finish();
}
})
.create().show();
}
#Override
protected void onPause() {
super.onPause();
Log.d(LOG_TAG, "onPause: editText is " + mEditText.getText());
}
}
and layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="false"
android:text="#string/hello_world"
tools:context=".MainActivity" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textMultiLine" />
</RelativeLayout>
There is an AlertDialog involved which's layout is this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:paddingLeft="20dp" android:paddingRight="20dp" android:paddingBottom="20dp" android:paddingTop="15dp" android:layout_gravity="top">
<TextView android:id="#+id/text" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textColor="#FFF"
android:gravity="top" android:textSize="16sp" android:paddingBottom="20dp"/>
<EditText
android:id="#+id/editTextDialog"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus></requestFocus>
</EditText>
</LinearLayout>
Now the steps are these:
Start activity in portrait orientation. A dialog pops up containing an EditText, prefilled with "Hello World!"
Append "zzz" to "Hello world!"
Press OK. "Hello world!zzz" is now assigned to the TextView on the Activity.
Now rotate the device to landscape. In onPause, mEditText.getText() now returns "zzz" although mEditText was not touched at all.
Any ideas? My expectation is that mEditText.getText() always returns "". If you repeat these steps but trigger onPause() by pressing back instead of rotating the device, getText() indeed does return "" as expected. Why not when rotating the device?
Additional note: I noticed that the soft keyboard seems to be necessary for the issue to appear. On an emulator with "Keyboard support = yes", the issue doesn't show up.
I had the same kind of issue with EditText. Looking in forums, I found that setting android:inputType="textNoSuggestions" fixes the issue, I don't know exactly how it works but, it worked fine on the Motorola Et1 tablet(Android 2.3).
Am trying to get the back button in my dialog to go back to the original screen. I don't know if I have all the imports that I need. Can someone tell me where I am going wrong?
Java code:
package my.dlog;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
public class DlogActivity extends Activity {
/** Called when the activity is first created. */
Dialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dialog = new Dialog(this);
dialog.setContentView(R.layout.main2);
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onBackPressed() {
Intent intent = new Intent(DlogActivity.this, DlogActivity.class);
startActivity(intent);
finish();
}
public void onClick(View v) {
dialog.show();
}
});
}
}
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:minHeight="400dp"
android:minWidth="300dp" android:background="#drawable/mint1">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<ImageView
android:layout_width="236dp"
android:layout_height="220dp"
android:layout_marginRight="100dp" android:background="#drawable/carsee"/>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</RelativeLayout>
</LinearLayout>
b.setOnClickListener(new OnClickListener() {
public void onBackPressed() {
dialog.cancel();
// Simply Dismiss the dialog to make it close and return to back..
/*What you are using is not a valid construct */
}
Also make sure that button1 in in main layout as you have used findViewById(R.id.button1) directly for set content view
Well normally the back button works just without any help from us. If you take the
public void onBackPressed() {
Intent intent = new Intent(DlogActivity.this, DlogActivity.class);
startActivity(intent);
finish();
}
out, what happens when you press 'back'? If this is not what you want, then what do you wnat to happen? If there are no errors, I would think you have the required imports.
Cliff
How would one set the button1 variable to true in the ReadButtons method and have it be used in the onCreate method/class?
I am a noob and have spent many hours trying to figure this out. I have no idea where to look for the answer any further. I know I may be way off in my understanding of how this works. But I don't know how to correct that misunderstanding. My background is in C and other procedural programming languages. Thank you kindly for your help.
package com.test;
// This is being run on Eclipse Helios with ADK set to Android 2.2
// and a 10 inch landscape display tablet PC.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.Boolean;
public class ButtonTestActivity extends Activity {
public static Boolean button1 = false, button2 = false;
public static String myText="Drat";
TextView textV_Test_Display;
public void ReadButtons(){
Button btn_button1_Ref = (Button) findViewById(R.id.btn_button1);
btn_button1_Ref.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myText="YAY!";
button1 = true;
// if(button1) textV_Test_Display.setText(myText);
//
// When I uncomment the above, it works as I desire visually.
//
// How do I set button1=true here and have
// the value carry back to the onCreate class?
//
//
Toast.makeText(v.getContext(), "Button 1", Toast.LENGTH_SHORT)
.show();
}
});
Button btn_button2_Ref = (Button) findViewById(R.id.btn_button2);
btn_button2_Ref.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myText="WOOT!";
button2 = true;
// if(button2) textV_Test_Display.setText(myText);
//
// When I uncomment the above, it works as I desire visually.
//
// How do I set button2=true here and have
// the value carry back to the onCreate class?
//
//
Toast.makeText(v.getContext(), "Button 2", Toast.LENGTH_SHORT)
.show();
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textV_Test_Display = (TextView)findViewById(R.id.txtV_ID_Test_Data);
ReadButtons();
if(button1 || button2) textV_Test_Display.setText(myText);
// This does not display myText.
// I am not able to carry the button1 or button2 variables to
// this part of the program.
// textV_Test_Display.setText(myText);
// When uncommented, this displays the word "Drat".
// When commented out, the word "nope" is displayed.
// In the main.xml file the text is set to the word "nope"
// This tells me this command works as expected.
}
}
This is the main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#FF000FFF"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button android:id="#+id/btn_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:height="50dp"
android:text="Button 1"
android:width="140dp"
android:textSize="16dp"
android:layout_marginTop="160dp"
android:layout_marginLeft="220dp"></Button>
<Button android:id="#+id/btn_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:height="50dp"
android:text="Button 2"
android:width="140dp"
android:textSize="16dp"
android:layout_marginTop="160dp"
android:layout_marginLeft="450dp"></Button>
<TextView android:id="#+id/txtV_ID_Test_Data"
android:gravity="center"
android:textSize="28dp"
android:textStyle="bold"
android:typeface="sans"
android:textColor="#FFFFFFFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="50dp"
android:height="50dp"
android:width="120dp"
android:text="nope"
android:layout_marginLeft="338dp"
android:background="#F00FF0F0"
></TextView>
</RelativeLayout>
Thanks
You are setting button1 = true in the onClick event. To be honest your code is pretty strange, I would take a look at some tutorials to see the correct way to do things in OO programming.
there is a couple of problems here.
You are setting the button to true in the listener, but that code will not be executed until the button is clicked.
you are trying to read the button1&button2 values in the on create method but so this code executes before the code in you listeners have exectued (because they haven't been clicked)
It look like you want to display some text based on weather either button is clicked: SO do this
make an update method
public void update() {
if(button1 || button2) textV_Test_Display.setText(myText);
}
called update() after you have set your variables in the button listener.