I am trying to create a simple user search page for my app. I tried to create a ParseQuery and display results in a Listview in my main activity page. However, when I run program, I could not get a result of a search, program displays nothing. I will be happy if I get an answer.
Here is my MainActivity.java;
package com.example.searchtest;
import java.util.ArrayList;
import java.util.List;
import com.parse.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
private Button search;
private EditText searchArea;
private ListView userList;
private String uName;
private ArrayAdapter<ParseUser> mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "WHz2GmkGFIUxBir6ZEDt2FIG4WUcE1kfKZmPayxy", "IAs1RCaRt5LM1E1ZW7LFXy5uDjtZEQ5CDa3LKJt2");
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.searchButton);
searchArea = (EditText) findViewById(R.id.searchField);
userList = (ListView) findViewById(R.id.results);
mainAdapter = new ArrayAdapter<ParseUser>(this, R.layout.activity_main, R.layout.search_list );
//mainAdapter.setTextKey("username");
userList.setAdapter(mainAdapter);
//mainAdapter.loadObjects();
uName = searchArea.getText().toString();
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", uName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
for(int i=0; i<objects.size();i++)
{
mainAdapter.add((ParseUser)objects.get(i));
}
} else {
// Something went wrong.
e.printStackTrace();
}
}
});
userList.setAdapter(mainAdapter);
}
});
}
#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);
}
}
And my main activity xml file;
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.searchtest.MainActivity" >
<EditText
android:id="#+id/searchField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="Search" />
<ListView
android:id="#+id/results"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp" >
</ListView>
</RelativeLayout>
I solved this problem. Here is updated version of code;
package com.example.searchtest;
import java.util.ArrayList;
import java.util.List;
import com.parse.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Button search;
private EditText searchArea;
private ListView userList;
//private String uName;
private ArrayAdapter<ParseUser> mainAdapter;
private ArrayList<ParseUser> resultList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "WHz2GmkGFIUxBir6ZEDt2FIG4WUcE1kfKZmPayxy", "IAs1RCaRt5LM1E1ZW7LFXy5uDjtZEQ5CDa3LKJt2");
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.searchButton);
searchArea = (EditText) findViewById(R.id.searchField);
userList = (ListView) findViewById(R.id.userResultList);
resultList = new ArrayList<ParseUser>();
mainAdapter = new ArrayAdapter<ParseUser>(this, R.layout.list_item, R.id.user_results,resultList);
//mainAdapter.setTextKey("username");
//userList.setAdapter(mainAdapter);
//mainAdapter.loadObjects();
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String uName = searchArea.getText().toString();
final ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", uName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
for(int i=0; i<objects.size();i++)
{
resultList.add((ParseUser)objects.get(i));
}
userList.setAdapter(mainAdapter);
Toast.makeText(getApplicationContext(), "User is Found",
Toast.LENGTH_LONG).show();
} else {
// Something went wrong.
e.printStackTrace();
Toast.makeText(getApplicationContext(), "User is not Found",
Toast.LENGTH_LONG).show();
}
}
});
userList.setAdapter(mainAdapter);
}
});
}
#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);
}
}
Moreover I need one more xml file to display the list. it is list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Single ListItem -->
<!-- Product Name -->
<TextView android:id="#+id/user_results"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
</LinearLayout>
and main xml file, activity_main.xml;
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.searchtest.MainActivity" >
<EditText
android:id="#+id/searchField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="Search" />
<ListView
android:id="#+id/userResultList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/searchField"
android:layout_below="#+id/searchField"
android:layout_marginTop="39dp" >
</ListView>
</RelativeLayout>
put uName = searchArea.getText().toString(); inside the listener, you are setting uName only once when the view is created, so it will be empty. You need to get the text after the user enters input and the button is clicked.
Related
I have problem with ActionBar in my fragment. It's invisible in it, so I can't execute getActionBar().setDisplayHomeAsUpEnabled(true); in my SignUpActivity.java. In every other Activity (not Fragment) it's visible.
Could You tell me what I am doing wrong? Probably something is missing.
fragment_sign_up.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
tools:context="com.msh.organizer.SignUpActivity">
<EditText
android:layout_below="#id/toolbar"
android:id="#+id/nickname_et"
android:hint="#string/nickname"
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/email_et"
android:hint="#string/mail"
android:layout_marginTop="5dp"
android:layout_below="#id/nickname_et"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/password_et"
android:hint="#string/password"
android:inputType="textPassword"
android:layout_marginTop="5dp"
android:layout_below="#id/email_et"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/sign_up_btn"
android:layout_marginTop="15dp"
android:layout_below="#id/password_et"
android:text="#string/sign_up"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
activity_sign_up.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.msh.organizer.SignUpActivity"
tools:ignore="MergeRootFrame" />
SignUpActivity.java
package com.msh.organizer;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class SignUpActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//getActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new SignUpFragment())
.commit();
}
//Toast.makeText(this,"Sign Up", Toast.LENGTH_LONG).show();
}
#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);
}
}
SignUpFragment.java
package com.msh.organizer;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class SignUpFragment extends Fragment implements View.OnClickListener {
private Button mSignUpButton;
private EditText mNickNameEditText;
private EditText mEmailEditText;
private EditText mPasswordEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sign_up, container, false);
mSignUpButton = (Button) rootView.findViewById(R.id.sign_up_btn);
mNickNameEditText = (EditText) rootView.findViewById(R.id.nickname_et);
mEmailEditText = (EditText) rootView.findViewById(R.id.email_et);
mPasswordEditText = (EditText) rootView.findViewById(R.id.password_et);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mSignUpButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_up_btn:
trySignUp();
break;
}
}
private void trySignUp() {
String nickname = mNickNameEditText.getText().toString();
String email = mEmailEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
boolean failed = false;
if (TextUtils.isEmpty(nickname)){
mNickNameEditText.setError("Nickname cannnot be empty!");
failed = true;
}
if (TextUtils.isEmpty(password)){
mPasswordEditText.setError("Password cannnot be empty!");
failed = true;
}
if (TextUtils.isEmpty(email)){
mEmailEditText.setError("Email cannnot be empty!");
failed = true;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
mEmailEditText.setError("Inwalid E-mail address!");
failed = true;
}
if (!failed){
signUp(nickname, email, password);
}
}
private void signUp(String nickname, String email, String password) {
ParseUser user = new ParseUser();
user.setUsername(email);
user.setPassword(password);
user.setEmail(email);
// other fields can be set just like with ParseObject
user.put("nickname", nickname);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
if (getActivity() != null){
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
}
} else {
if (getActivity() != null) {
Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
}
}
You can use Toolbar inside an AppBarLayout in your activity:
SignUpActivity.java
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
...
activity_sign_up.xml
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.msh.organizer.SignUpActivity"
tools:ignore="MergeRootFrame" />
i have given the code here . and when i run it in genymotion it just stops working. please help .
i dont see any display in logcat also . it remains blank and the emulator only shows an error that is "unfortulately, SharedprefrencEexample has stoped working. and the app dont even starts. so i dont get any clue of what might be the error in this code .
here i have used the reference creation at the start and i think it might be the error. so please do see the code and help me.
thanks.
Main_Activity
package com.example.sharedprefrenceexample;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText name,phone,email;
Button submit;
Intent intent;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText) findViewById(R.id.editText1);
phone=(EditText) findViewById(R.id.editText2);
email=(EditText) findViewById(R.id.editText3);
submit=(Button) findViewById(R.id.button1);
submit.setText("#string/button_name_activity_one");
name.setHint("name");
phone.setHint("phone");
email.setHint("email id");
sharedPreferences=getSharedPreferences("#string/database_name", MODE_PRIVATE);
editor=sharedPreferences.edit();
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
editor.putString("name", name.getText().toString());
editor.putString("phone", phone.getText().toString());
editor.commit();
intent=new Intent(MainActivity.this,Secondactivity.class);
intent.putExtra("email", email.getText().toString());
startActivity(intent);
}
});
}
#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);
}
}
activity_main.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.sharedprefrenceexample.MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1"
android:ems="10"
android:inputType="numberPassword" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText2"
android:layout_below="#+id/editText2"
android:ems="10"
android:inputType="textEmailAddress" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="#string/button_name_activity_one" />
</RelativeLayout>
secondactivity
package com.example.sharedprefrenceexample;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Secondactivity extends Activity {
TextView result;
SharedPreferences sharedPreferences;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondactivity);
result=(TextView) findViewById(R.id.textView1);
sharedPreferences=getSharedPreferences("database", MODE_PRIVATE);
String res = null;
res=res+sharedPreferences.getString("name", "no name");
res=res+sharedPreferences.getString("phone", "no phone");
intent=getIntent();
res=res+intent.getStringExtra("email");
result.setText(res);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.secondactivity, 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);
}
}
activity_secondactivity.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.sharedprefrenceexample.Secondactivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
submit.setText("#string/button_name_activity_one");
// (...)
sharedPreferences=getSharedPreferences("#string/database_name", MODE_PRIVATE);
That syntax is only valid in XML. In Java code, to use a string reference you should use
submit.setText(R.string.button_name_activity_one);
So fix those string references and it should work.
More info: String resources # Android Developers
In the following code, I'm trying to pass numerical data from two EditText fields to two variables, perform a computation (multiplication), then have the result displayed in a third EditText field.
I have tried two different scenarios but whenever I try running the code, the the program crashes. Below is the first scenario:
package edu.arizona.uas.fonji.bmicalculator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.text.DecimalFormat;
public class BmiCalculator extends ActionBarActivity {
Button reset_button, calculate_button;
EditText height_text;
EditText weight_text;
EditText bmi_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmi_calculator);
EditText height_text = (EditText)findViewById(R.id.height); //get value from height text box
String height_string = height_text.getText().toString(); //convert to string
final float height_value = Integer.parseInt(height_string); //convert to number
EditText weight_text = (EditText)findViewById(R.id.weight); //get value from weight text box
String weight_string = weight_text.getText().toString(); //convert to string
final float weight_value = Integer.parseInt(weight_string); //convert to number
calculate_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
DecimalFormat df = new DecimalFormat("#.0");
double adouble = weight_value*height_value;
bmi_text.setText("Number is " + df.format(adouble));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bmi_calculator, 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);
}
}
Having the impression this code crashes because I try to collect the data and convert (height_text and weight_text) outside OnClickListener(), resulting in possibly no data being collected at all I modified it in the scenario below and I also tried to safeguard from run time exceptions such as invalid input as follows:
package edu.arizona.uas.fonji.bmicalculator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
public class BmiCalculator extends ActionBarActivity {
Button reset_button, calculate_button;
EditText height_text;
EditText weight_text;
EditText bmi_text;
TextView myTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmi_calculator);
calculate_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
float height_value = 0;
float weight_value = 0;
EditText height_text = (EditText)findViewById(R.id.height); //get value from height text box
try{
String height_string = height_text.getText().toString(); //convert to string
height_value = Integer.parseInt(height_string); //convert to number
}catch(Exception e){
myTextView.setText("Error, invalid character");
}
EditText weight_text = (EditText)findViewById(R.id.weight); //get value from weight text box
try{
String weight_string = weight_text.getText().toString(); //convert to string
weight_value = Integer.parseInt(weight_string); //convert to number
}catch(Exception e){
myTextView.setText("Error, Invalid character");
}
DecimalFormat df = new DecimalFormat("#.0");
double adouble = weight_value*height_value;
bmi_text.setText("Number is " + df.format(adouble));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bmi_calculator, 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);
}
}
In either case, I still can't get this to work properly. How can I fix this problem? The .xml code is listed below:
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="edu.arizona.uas.fonji.bmicalculator.BmiCalculator" >
<Button
android:id="#+id/reset"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_above="#+id/calculate"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="26dp"
android:text="reset" />
<Button
android:id="#+id/calculate"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="37dp"
android:text="calculate" />
<EditText
android:id="#+id/height"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="number"
android:hint="height" >
</EditText>
<EditText
android:id="#+id/weight"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/height"
android:layout_below="#+id/height"
android:ems="10"
android:hint="weight"
android:inputType="number"
/>
<EditText
android:id="#+id/bmi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/weight"
android:layout_below="#+id/weight"
android:layout_marginTop="36dp"
android:ems="10"
android:hint="bmi">
<requestFocus />
</EditText>
<TextView
android:id="#+id/report_error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/reset"
android:layout_alignTop="#+id/height"
android:padding="24dp"
/>
</RelativeLayout>
I'm currently working on making a simple conversion program and im trying to have the user select from a list of items "binary, decimal..." from one spinner menu and then select a second choice "binary, decimal.." and then use the text field to the right of the spinners to input the value and then hit a "convert" button and it spit out the conversion.
So far, ive been able to build the 2 text fields and the conversion button and have THAT work but, i can't seem to figure out how to make the text fields work with the selection on the spinner menu.
Any suggestions? This is what i currently have---______------______----- THANKS IN ADVANCE :)
MainActivity
package com.overworldinnovations.datatool;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
//import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
//import android.os.Build;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Spinner spinner1, spinner2;
private Button buttonConvert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.overworldinnovations.datatool.MainActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonConvert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:text="Convert" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="108dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/spinner1"
android:layout_alignParentRight="true"
android:layout_marginBottom="16dp"
android:layout_marginRight="50dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/spinner2"
android:layout_alignLeft="#+id/textView1"
android:layout_marginBottom="16dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
strings
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Data Tool</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="convert">Convert</string>
<string name="data_tool_is_an_application_that_converts_binary_to_decimal_d">Data Tool is an application that converts Binary to Decimal :D</string>
<string name ="country_prompt">Choose a country</string>
<string-array name = "type_arrays">
<item >Decimal</item>
<item >Binary</item>
<item >Hexidecimal</item>
</string-array>
</resources>
CustomOnItemSelectedListener
package com.overworldinnovations.datatool;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
I'm making a program for Android using Eclipse. Here is my code for MainAcitvity.java:
package com.example.changeme;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button set = (Button)findViewById(R.id.set);
TextView out = (TextView)findViewById(R.id.out);
EditText in = (EditText)findViewById(R.id.input);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
set.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setcontent();
}
});
}
public void setcontent()
{
String con = in.getText().toString();
out.setText(con);
}
#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 false;
}
}
Layout for main activity :
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/set"
android:layout_alignParentBottom="true"
android:layout_marginBottom="37dp"
android:text="#string/Change"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/set"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/input"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="#string/Set" />
<EditText
android:id="#+id/input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:ems="10"
android:inputType="textPersonName" />
It crashes when I run the program on my N4.
You need to inflate your layout before retrieve your elements, otherwise findViewById will return null and hence the line set.setOnClickListener(/**/); will throw a NullPointerException which make your app crashing.
Button set;
TextView out;
EditText in;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //<-- the layout is inflated, i.e it's rendered
/******************************************************/
//Now you can retrieve your elements from this layout
set = (Button)findViewById(R.id.set);
out = (TextView)findViewById(R.id.out);
in = (EditText)findViewById(R.id.input);
/*****************************************************/
set.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setcontent();
}
});
}