hide button if text length is < 1 in android studio - java

I'm new to Android and Java and I'm busy editing an existing app. I am trying to hide a button if no text is getting pulled in from a webservice. I have made it work with another button when the text is being populated
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
but when I used:
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
nothing seems to happen.
I don't know if the code snippet is in the wrong place or something else is overwriting the code. Here is my activity code:
package com.example.dsouchon.myapplication;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
if(Local.isSet(getApplicationContext(), "LoggedIn"))
{
String loggedInUser = Local.Get(getApplicationContext(), "LoggedIn");
if(loggedInUser.length()>0)
{
buttonEventSetup.setVisibility(View.VISIBLE);
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
if(Local.isSet(getApplicationContext(), "EventName"))
{
String event = Local.Get(getApplicationContext(), "EventName");
TextView textEvent = (TextView) findViewById(R.id.textEventName);
textEvent.setText( event);
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(true);
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
}
else
{
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(false);
}
if(Local.isSet(getApplicationContext(), "EventImage"))
{
TextView textEvent = (TextView) findViewById(R.id.textEventName);
String result = Local.Get(getApplicationContext(), "EventImage");
ImageView imageViewEventImage = (ImageView)findViewById(R.id.imageViewEventImage);
byte[] decodedString = Base64.decode(result, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageViewEventImage.setImageBitmap(decodedByte);
}
}
#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_main2, 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);
}
public void setupEvent(View view) {
Intent intent = new Intent(MainActivity.this, SetupEvent.class );
finish();
startActivity(intent);
}
public void accessControl(View view) {
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.GONE);
Intent intent = new Intent(MainActivity.this, MainActivity21.class );
finish();
startActivity(intent);
}
public void Logoff(View view) {
Local.Set(getApplicationContext(), "LoggedIn", "");
}
public void Login(View view) {
final AlertDialog ad=new AlertDialog.Builder(this).create();
MySOAPCallActivity cs = new MySOAPCallActivity();
try {
EditText userName = (EditText) findViewById(R.id.editUserName);
EditText password = (EditText) findViewById(R.id.editPassword);
String user = userName.getText().toString();
String pwd = password.getText().toString();
LoginParams params = new LoginParams(cs, user, pwd);
Local.Set(getApplicationContext(), "UserName", user);
Local.Set(getApplicationContext(), "Password", pwd);
new CallSoapLogin().execute(params);
// new CallSoapGetCurrentEvents().execute(params);
} catch (Exception ex) {
ad.setTitle("Error!");
ad.setMessage(ex.toString());
}
ad.show();
}
public class CallSoapLogin extends AsyncTask<LoginParams, Void, String> {
private Exception exception;
#Override
protected String doInBackground(LoginParams... params) {
return params[0].foo.Login(params[0].username, params[0].password);
}
protected void onPostExecute(String result) {
// TODO: check this.exception
// TODO: do something with the feed
try {
TextView loginResult =(TextView)findViewById(R.id.labelLoginResult);
loginResult.setVisibility(View.VISIBLE);
loginResult.setText(result);
// Button buttonUnsetEvent = (Button)findViewById(R.id.buttonUnsetEvent);
// buttonUnsetEvent.setEnabled(true);
//Spinner spinner2 = (Spinner)findViewById(R.id.spinner2);
//spinner2.setEnabled(true);
boolean LoginSuccessful = false;
if(result.toLowerCase().contains("success"))
{
LoginSuccessful = true;
}
if (LoginSuccessful)
{
String user = Local.Get(getApplicationContext(), "UserName");
Local.Set(getApplicationContext(), "LoggedIn", user);
LinearLayout layoutLoggedIn = (LinearLayout)findViewById(R.id.layoutLoggedIn);
layoutLoggedIn.setVisibility(View.VISIBLE);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.VISIBLE);
LinearLayout layoutLogIn = (LinearLayout)findViewById(R.id.layoutLogIn);
layoutLogIn.setVisibility(View.VISIBLE);
}
} catch (Exception ex) {
String e3 = ex.toString();
}
}
}
private static class LoginParams {
MySOAPCallActivity foo;
String username;
String password;
LoginParams(MySOAPCallActivity foo, String username, String password) {
this.foo = foo;
this.username = username;
this.password = password;
}
}
}

You are getting the length of Textview that will not work.Use the text length.This should work
String event = Local.Get(getApplicationContext(), "EventName");
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (event.length() > 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (event.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}

In your code above textEvent is not a string value. It is an Object of type TextView. length() in this case will not return the length of the text contained within that element. You will need to explicitly get the text string before you can get the length of it. This is acquired using the getText() method on the TextView.
Your code should look like the following:
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.getText().length() >= 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (textEvent.getText().length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
You also have INVISIBLE on both cases in your posted code example.
Note that your code also does not handle cases where the text length == 1. You could simplify the whole block with the following.
Note: any value != 0 is classed as true
buttonEventSetup.setVisibility(textEvent.getText().length() ? View.VISIBLE : View.INVISIBLE);

Related

NullPointerException when I select Items on Spinner

I have two spinners, one with a list of countries(countrySpinner) and the other with a list of provinces(stateSpinner). I want the stateSpinner to be active only if Nigeria is selected on the countrySpinner, and for the other countries on to be selectable without selecting item on the stateSpinner. My code seam to work when I select Nigerian on the countrySpinner and a corresponding state, but I GET THIS NullPointerException : println needs a message, anytime I select a country other than Nigeria on the countrySpinner. Not quite sure of what to do to get pass here. I Would appreciate any help. My code below.enter code here
public class RegisterActivity extends AppCompatActivity {
Spinner countrySpinner, stateSpinner;
List<String> countryList;
ArrayList<String> stateList;
ArrayAdapter<String> stateAdapter;
String countrySelected, stateSelected, gender;
TextInputLayout name, email, password, confirmPw;
RadioGroup genderOptionGroup;
RadioButton genderOptionBtn;
TextView countryUnCheckedWarning;
Button nextButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);nextButton = findViewById(R.id.createAccNext);
countryUnCheckedWarning = findViewById(R.id.countrySelectW);
genderOptionGroup = findViewById(R.id.gender_group);
name = findViewById(R.id.fullNameInputLayout);
email = findViewById(R.id.emailInputLayout);
password = findViewById(R.id.pwInputLayout);
confirmPw = findViewById(R.id.cpwInputLayout);
countrySpinner = findViewById(R.id.countryDropDown);
stateSpinner = findViewById(R.id.stateDropDown);
stateList = new ArrayList<String>(Arrays.asList("Select State of Residence", "Abia", "Abuja", "Adamawa", "Akwa Ibom", "Anambra",
"Bauchi", "Bayelsa", "Benue", "Borno", "Cross River", "Delta", "Ebonyi", "Enugu", "Edo",
"Ekiti", "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara",
"Lagos", "Nasarawa", "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto",
"Taraba", "Yobe", "Zamfara", "Territory"));
stateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stateList);
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stateSpinner.setAdapter(stateAdapter);
countryList = new ArrayList<String>();
countryList.add(0, "Select Country");
countryList.add("Gambia");
countryList.add("Sierra Leone");
countryList.add("Liberia");
countryList.add("Ghana");
countryList.add("Nigeria");
countryList.add("South Africa");
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countryList);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
countrySpinner.setAdapter(countryAdapter);
// Country Spinner
countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!(parent.getItemAtPosition(position).equals("Nigeria")) && !(parent.getItemAtPosition(position).equals("Select Country"))){
// Country other than Nigeria has been selected
countrySelected = parent.getItemAtPosition(position).toString();
Log.i("Country Selected is",countrySelected);
nextButton.setEnabled(true);
nextButton.setBackgroundColor(getResources().getColor(R.color.red));
}else if (parent.getItemAtPosition(position).equals("Nigeria")){
// Nigeria is selected
stateSpinner.setAlpha(1);
countrySelected = "Nigeria";
nextButton.setEnabled(false);
nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
}else {
countrySelected = "";
nextButton.setEnabled(false);
nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// State SpinnerGroup
stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getItemAtPosition(position).equals("Select State of Residence")) {
nextButton.setEnabled(false);
nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
} else {
stateSelected = parent.getItemAtPosition(position).toString();
nextButton.setEnabled(true);
nextButton.setBackgroundColor(getResources().getColor(R.color.red));
Log.i("State Selected", stateSelected);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
// Name, Email and Password Validation MTDs Below
private boolean validateName() {
String nameInpute = name.getEditText().getText().toString().trim();
// check for non empty field
if (nameInpute.isEmpty()) {
name.setError("Name Field Can't be empty");
return false;
} else if (nameInpute.length() < 5) {
name.setError("Name is too short");
return false;
} else {
name.setError(null);
return true;
}
}
private boolean validateEmail() {
String emailInpute = email.getEditText().getText().toString().trim();
// Now we check for non empty field
if (emailInpute.isEmpty()) {
email.setError("E-mail Field Can't be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(emailInpute).matches()) {
email.setError("Please enter a valid email address");
return false;
} else {
// Remove Error and return true
email.setError(null);
return true;
}
}
private boolean validatePassword() {
String passwordInpute = password.getEditText().getText().toString().trim();
// check for non empty field
if (passwordInpute.isEmpty()) {
password.setError("Password Field Can't be empty");
return false;
} else if (passwordInpute.length() > 15) {
password.setError("Password is too long");
return false;
} else {
password.setError(null);
return true;
}
}
private boolean validateCPassword() {
String passwordInpute = password.getEditText().getText().toString().trim();
String confirmPWInpute = confirmPw.getEditText().getText().toString().trim();
// check for non empty field
if (confirmPWInpute.isEmpty()) {
confirmPw.setError("Password Field Can't be empty");
return false;
} else if (!confirmPWInpute.equals(passwordInpute)) {
confirmPw.setError("Password does not match");
return false;
} else {
password.setError(null);
return true;
}
}
public void moveToNextOnReg(View view) {
// check for or validations
if (!validateName() | !validateEmail() | !validatePassword() | !validateCPassword()) {
return; }
// put whatever result needed here
String fullName = name.getEditText().getText().toString().trim();
String emailRegistered = email.getEditText().getText().toString().trim();
String passwordRegistered = password.getEditText().getText().toString().trim();
Log.i("Name", fullName);
Log.i("E-mail", emailRegistered);
Log.i("Password", passwordRegistered);
Log.i("Country", countrySelected);
Log.i("State", stateSelected);
Log.i("Sex", gender);
Intent intentNext = new Intent(getApplicationContext(),ToNextActivity.class);
startActivity(intentNext);
}
public void backToOnboarding(View view) {
Intent intent = new Intent(getApplicationContext(), OnboardingActivity.class);
startActivity(intent);
finish();
}
public void onGenderSelected(View view){
int radioId = genderOptionGroup.getCheckedRadioButtonId();
genderOptionBtn = findViewById(radioId);
gender = genderOptionBtn.getText().toString();
Log.i("Gender Selceted", genderOptionBtn.getText().toString());
}
}
You don't seem to initialize nextButton in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);nextButton = findViewById(R.id.createAccNext);
countryUnCheckedWarning = findViewById(R.id.countrySelectW);
genderOptionGroup = findViewById(R.id.gender_group);
name = findViewById(R.id.fullNameInputLayout);
email = findViewById(R.id.emailInputLayout);
password = findViewById(R.id.pwInputLayout);
confirmPw = findViewById(R.id.cpwInputLayout);
countrySpinner = findViewById(R.id.countryDropDown);
stateSpinner = findViewById(R.id.stateDropDown);
//here.....
nextButton = findViewById(...............);//what ever the id is in xml

JSON Parsing error at the runtime

I am the student and i'm learning android, i got following error and i can't find out the solution of that error, plz help me to solve that error. Thank you...
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.sumit.json1/com.sumit.json1.ParseJSON}:
java.lang.NullPointerException: Attempt to invoke virtual method
'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object
reference.
There is no issue of connectivity to database. My php code is which is hosted on hostinger.in
<?
//these are the server details
//the username is root by default in case of xampp
//password is nothing by default
//and lastly we have the database named android. if your database name is
different you have to change it
$servername = "mysql.hostinger.in";
$username = "username";
$password = "*********";
$database = "database_name";
//creating a new connection object using mysqli
$conn = new mysqli($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message
causing the error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//if everything is fine
//creating an array for storing the data
$heroes = array();
//this is our sql query
$sql = "SELECT id, name, email, username, password, gender, lat, lon FROM
appusers;";
//creating an statment with the query
$stmt = $conn->prepare($sql);
//executing that statment
$stmt->execute();
//binding results for that statment
$stmt->bind_result($id, $name, $email, $username, $password, $gender, $lat,
$lon);
//looping through all the records
while($stmt->fetch()){
//pushing fetched data in an array
$temp = [
'id'=>$id,
'name'=>$name,
'email'=>$email,
'username'=>$username,
'password'=>$password,
'gender'=>$gender,
'lat'=>$lat,
'lon'=>$lon
];
//pushing the array inside the hero array
array_push($heroes, $temp);
}
//displaying the data in json format
echo json_encode($heroes);
For parsing json my android code is i.e. ParseJSON.java
public class ParseJSON extends ActionBarActivity implements
View.OnClickListener{
private String myJSONString;
private static final String JSON_ARRAY ="heroes";
private static final String ID = "id";
private static final String NAME= "name";
private static final String EMAIL = "email";
private static final String USERNAME= "username";
private static final String PASSWORD = "password";
private static final String GENDER = "gender";
private static final String LAT = "lat";
private static final String LON = "lon";
private JSONArray users = null;
private int TRACK = 0;
private EditText editTextId;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextUserName;
private EditText editTextPassword;
private EditText editTextGender;
private EditText editTextLat;
private EditText editTextLon;
Button btnPrev;
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parse_json);
Intent intent = getIntent();
myJSONString = intent.getStringExtra(MainActivity.MY_JSON);
editTextId = (EditText) findViewById(R.id.editTextID);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextUserName = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextGender = (EditText) findViewById(R.id.editTextGender);
editTextLat = (EditText) findViewById(R.id.editTextLat);
editTextLon = (EditText) findViewById(R.id.editTextLon);
btnPrev = (Button) findViewById(R.id.buttonPrev);
btnNext = (Button) findViewById(R.id.buttonNext);
btnPrev.setOnClickListener(this);
btnNext.setOnClickListener(this);
extractJSON();
showData();
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(myJSONString);
users = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK<users.length()){
TRACK++;
}
showData();
}
private void movePrev(){
if(TRACK>0){
TRACK--;
}
showData();
}
private void showData(){
try {
JSONObject jsonObject = users.getJSONObject(TRACK);
editTextId.setText(jsonObject.getString(ID));
editTextName.setText(jsonObject.getString(NAME));
editTextEmail.setText(jsonObject.getString(EMAIL));
editTextUserName.setText(jsonObject.getString(USERNAME));
editTextPassword.setText(jsonObject.getString(PASSWORD));
editTextGender.setText(jsonObject.getString(GENDER));
editTextLat.setText(jsonObject.getString(LAT));
editTextLon.setText(jsonObject.getString(LON));
} catch (JSONException e) {
e.printStackTrace();
}
}
#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_parse_json, 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);
}
#Override
public void onClick(View v) {
if(v == btnNext){
moveNext();
}
if(v == btnPrev){
movePrev();
}
}
}
In my android project MainActivity.java is given bellow if any error find out plz help me to resove
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private TextView textViewJSON;
private Button buttonGet;
private Button buttonParse;
public static final String MY_JSON ="MY_JSON";
private static final String JSON_URL = "http://mydatabasedb.16mb.com/JSON1/send-data1.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewJSON = (TextView) findViewById(R.id.textViewJSON);
textViewJSON.setMovementMethod(new ScrollingMovementMethod());
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonParse = (Button) findViewById(R.id.buttonParse);
buttonGet.setOnClickListener(this);
buttonParse.setOnClickListener(this);
}
#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_main, 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);
}
#Override
public void onClick(View v) {
if(v==buttonGet){
getJSON(JSON_URL);
}
if(v==buttonParse){
showParseActivity();
}
}
private void showParseActivity() {
Intent intent = new Intent(this, ParseJSON.class);
intent.putExtra(MY_JSON,textViewJSON.getText().toString());
startActivity(intent);
}
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait...",null,true,true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textViewJSON.setText(s);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
}
users = jsonObject.getJSONArray(JSON_ARRAY);
This attempts to parse a list at the "heroes" key, but there is no "heroes" key the JSON document. You are encoding a list, not an object.
Open the URL that returns the JSON in a browser, and the problem should be apparent.

InputStream does not want to read from a textfile android studio

I have problems with android programming in java, because it does not want to read from a text file. The problem is that the buttons do not add the text which I am trying to do in the async-class. Furthermore, the buttons which will show the text does not work, because when I press on a button the application stops working.
Short introduction of the program:
The application starts with a value sent to gameAction from a spinner, and from there it wil invoke a name on text-file which will be loaded into strings in an array-list, the class QuestionBox. Lastly it will questions will be made in GameAction class.
If something was unclear, please comment. And any help is appreciated! Excuse me for adding a lot of code, but I added it due to not knowing how to do.
public class QuestionBox extends AsyncTask<Object, Void, Object>{
private Context context;
private Callback callback;
private List<Question> mQuestions;
public QuestionBox(Context context,Callback callback)
{
mQuestions = new ArrayList<Question>();
this.callback=callback;
this.context= context;
}
public Callback getCallback(){
return callback;
}
#Override
protected Object doInBackground(Object... params) {
InputStream iS = null;
try {
iS = context.getAssets().open("hogskoleprovet.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Hit kom du");
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
String question, answer, answerOne, answerTwo, answerThree, answerFour;
try {
while (reader.readLine() != null) {
//reading some lines from resource file
question = reader.readLine();
answer = reader.readLine();
answerOne = reader.readLine();
answerTwo = reader.readLine();
answerThree = reader.readLine();
answerFour = reader.readLine();
Question q = new Question(question, answer, answerOne, answerTwo, answerThree, answerFour);
mQuestions.add(q);
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.close();
System.out.println("Hit kom du3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
public interface Callback{
public void notify_result(List<Question> question_list);
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
public int getQuestionsLeft() {
return mQuestions.size();
}
public Question getRandomQuestion() {
Random random = new Random();
int index = random.nextInt(mQuestions.size());
Question newQuestion = mQuestions.get(index);
mQuestions.remove(index);
return newQuestion;
}
}
Here is another method which the strings will be sent to:
public class gameAction extends ActionBarActivity implements QuestionBox.Callback{
private QuestionBox mQuestionBox;
private Question mCurrentQuestion;
private Context context;
private Callback callback;
#Override
public void notify_result(List<Question> question_list) {
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_action);
//Kod som kollar vad som skickades med när aktiviteten startades
Intent callingIntent = getIntent();
int index = callingIntent.getIntExtra("INDEX",0);
//Bestäm filnamn beroende på vad som skickades med
if(index==0){
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
}
else {
if (index == 1 ) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
} else if (index == 1) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
} else if (index == 2) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
}
}
}
public void setNewQuestion()
{
//Hämta en slumpmässig fråga från vår QuestionBox
//och lagra den i mCurrentQuestion
mCurrentQuestion = mQuestionBox.getRandomQuestion();
//Se till så att textfält och knappar visar den aktuella
//frågan
TextView questionTextView = (TextView) findViewById(R.id.questionTextView);
questionTextView.setText(mCurrentQuestion.getQuestion());
Button buttonOne = (Button) findViewById(R.id.buttonOne);
buttonOne.setText(mCurrentQuestion.getOptionOne());
Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
Button buttonThree = (Button) findViewById(R.id.buttonThree);
buttonThree.setText(mCurrentQuestion.getOptionThree());
Button buttonFour = (Button) findViewById(R.id.buttonFour);
buttonFour.setText(mCurrentQuestion.getOptionFour());
Button buttonNew = (Button) findViewById(R.id.buttonNew);
buttonOne.setEnabled(true);
buttonTwo.setEnabled(true);
buttonThree.setEnabled(true);
buttonFour.setEnabled(true);
buttonNew.setVisibility(View.INVISIBLE);
buttonOne.setText(mCurrentQuestion.getOptionOne());
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
buttonThree.setText(mCurrentQuestion.getOptionThree());
buttonFour.setText(mCurrentQuestion.getOptionFour());
}
public void quitTheGame(View v){
Intent intent = new Intent (this, MainActivity.class);
Button butttonQuit = (Button) findViewById(R.id.buttonFive);
startActivity(intent);
}
public void answerClick(View V)
{
Button answerButton = (Button)V;
Button buttonOne = (Button) findViewById(R.id.buttonOne);
buttonOne.setText(mCurrentQuestion.getOptionOne());
Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
Button buttonThree = (Button) findViewById(R.id.buttonThree);
buttonThree.setText(mCurrentQuestion.getOptionThree());
Button buttonFour = (Button) findViewById(R.id.buttonFour);
buttonFour.setText(mCurrentQuestion.getOptionFour());
Button buttonNew = (Button) findViewById(R.id.buttonNew);
buttonOne.setEnabled(false);
buttonTwo.setEnabled(false);
buttonThree.setEnabled(false);
buttonFour.setEnabled(false);
buttonNew.setVisibility(View.VISIBLE);
}
public void newClick(View v){
if(mQuestionBox.getQuestionsLeft()>0){
setNewQuestion();
}
else
{
Context context = getApplicationContext();
String text = "Slut på frågor!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.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_main, 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);
}
}
Here is the class for putting answer to correct options:
package com.example.arnpet.ultimatehogskoleprovet;
public class Question {
private String question;//Lagrar frågan
private String optionOne; //Lagrar svarsalternativ
private String optionTwo;
private String optionThree;
private String optionFour;
private String correctAnswer; //Lagrar det korrekta svaret
//konstruktor
public Question (String question, String optionOne, String optionTwo,
String optionThree, String optionFour, String correctAnswer)
{
this.question = question;
this.optionOne = optionOne;
this.optionTwo = optionTwo;
this.optionThree = optionThree;
this.optionFour = optionFour;
}
public String getQuestion() {
return question;
}
public String getOptionOne() {
return optionOne;
}
public String getOptionTwo() {
return optionTwo;
}
public String getOptionThree() {
return optionThree;
}
public String getOptionFour() {
return optionFour;
}
}
while (reader.readLine() != null)
Here you are reading a line of the file and throwing it away. Not what you want, unless your file is strangely structured with ignorable junk lines every so often.
The usual loop looks like this:
while ((line = reader.readLine()) != null)
and then using line in the controlled block.
Secondly, this is the only place you check for null, yet you have several other readLine() calls, any one of which can return null. So you run some risk of NPEs later in your code.

How to save information in multiple text boxes with save and load buttons

I'm trying to create a simple Android program that has text boxes for name, address, phone number, etc. When the user puts this information in and hits save it clears the text boxes, and when they hit the load button it retrieves the info. I know how to do it with one EditText box, but I can't figure out multiple. Can I do this inside one try/catch statement, or do I need more than one? This is what I have right now:
public class MainActivity extends ActionBarActivity {
private EditText textBoxName;
private EditText textBoxAddress;
private EditText textBoxCity;
private EditText textBoxPhone;
private EditText textBoxEmail;
private static final int READ_BLOCK_SIZE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textBoxName = (EditText) findViewById(R.id.txtName);
textBoxAddress = (EditText) findViewById(R.id.txtAddress);
textBoxCity = (EditText) findViewById(R.id.txtCity);
textBoxPhone = (EditText) findViewById(R.id.txtPhone);
textBoxEmail = (EditText) findViewById(R.id.txtEmail);
Button saveBtn = (Button) findViewById(R.id.btnSave);
Button loadBtn = (Button) findViewById(R.id.btnLoad);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strName = textBoxName.getText().toString();
String strAddress = textBoxAddress.getText().toString();
String strCity = textBoxCity.getText().toString();
String strPhone = textBoxPhone.getText().toString();
String strEmail = textBoxEmail.getText().toString();
try {
FileOutputStream fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//write the string to the file
osw.write(strName);
osw.flush();
osw.close();
//display file saved messages
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
//clears the EditText
textBoxName.setText("");
textBoxAddress.setText("");
textBoxCity.setText("");
textBoxPhone.setText("");
textBoxEmail.setText("");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
});
loadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try
{
FileInputStream fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = isr.read(inputBuffer))>0)
{
//convert the chars to a String
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
//set the EditText to the text that has been read
textBoxName.setText(s);
textBoxAddress.setText(s);
textBoxCity.setText(s);
textBoxPhone.setText(s);
textBoxEmail.setText(s);
Toast.makeText(getBaseContext(), "File loaded successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
});
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use Shared Preferences to store and retrieve information in Android.
you can use shared preferences for this purpose . Just put the value into shared preference and load when the user need this info like username and password saved locally into any login form.

How to validate to rating bar on Button click in Android?

I want to validation on RatingBar in Android. I have 5 rating Bar and 1 Button. I don't want to submit the data without pressed the rating bar. I want to take validation on Rating bar.
Can someone help me. How to take validation on Rating bar?
Here is my Activity code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rating_baar);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
addListenerOnRatingBar_one();
addListenerOnRatingBar_two();
addListenerOnRatingBar_three();
addListenerOnRatingBar_four();
addListenerOnRatingBar_five();
addListenerOnButton();
}
#SuppressLint("SimpleDateFormat")
public void addListenerOnButton() {
buttonSubmitRate = (Button) findViewById(R.id.button_SubmitRate);
buttonSubmitRate.setOnClickListener(new OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
if((etTaskName.getText().toString().isEmpty()))
etTaskName.setError("Field Can Not Be Empty !");
else if (!etTaskName.getText().toString().trim().matches("[a-zA-Z{ }]+"))
etTaskName.setError("Accept Alphabets Only.");
else {
strEmpName = textViewNAme.getText().toString().trim();
strTaskName = etTaskName.getText().toString().trim();
String strCurrentDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println("strCurrentDate = " + strCurrentDate);
String strCurrentMonth = new SimpleDateFormat("MMM").format(new Date());
System.out.println("strCurrentDate = " + strCurrentMonth);
String strCurrenYear = new SimpleDateFormat("yyyy").format(new Date());
System.out.println("strCurrenYear = " + strCurrenYear);
System.out.println("__________________________________________________________________________________");
databaseHelper.insertPerformance_Details(intentStr1, strEmpName,
strTaskName, rateVal_one,
rateVal_two, rateVal_three,
rateVal_four,rateVal_five,
strCurrentDate,strCurrentMonth,
strCurrenYear);
System.out.println("Data Add SuccesFully !!!!");
etTaskName.setText("");
Intent i = new Intent(RatingBaar_Class.this, Rating_Msg.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.anim_in,R.anim.anim_out);
}
}
});
}
public void addListenerOnRatingBar_one() {
ratingBar_one = (RatingBar) findViewById(R.id.ratingBar1);
ratingBar_one.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rateVal_one = String.valueOf(rating);
System.out.println(" rateVal_one = " + rateVal_one);
}
});
}
/* Exactly the same methods for four other rating bars, except for variable names */
public void addListenerOnRatingBar_two() { ... }
public void addListenerOnRatingBar_three() { ... }
public void addListenerOnRatingBar_four() { ... }
public void addListenerOnRatingBar_five() { ... }
At first set all rating bar to 0 value. Then on click to button, check if the value has altered in all of them. If so, only valid else invalid.
Also you can use listener to each rating bar and change value of some boolean variable to true
Example:
boolean flag1 = false;
boolean flag2 = false;
.... //similarly upto 5
Then in rating bar listener1
{
flag1 = true;
}
Similarly for all set flag to be true
And in button onClickListener do the following:
if(flag1 && flag2 && flag3 && flag4 && flag5){
//do your work
}else{
//display message that one of the rating bar hasn't been touched
}

Categories

Resources