I have recently started working in android studio, and I am trying to make the UI of an app before I add any SQL, because I don't want to learn a language for a program that won't work, but any way, I tried to use a TableLayout with text boxes, and take user input and insert it into that table. It does not work. I keep getting an error shown in the picture.[error shown][1]
package com.example.tj_n126.firstappattempt;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView lastNameDisplay = findViewById(R.id.lNameTxt);
TextView firstNameDisplay = findViewById(R.id.nameTxt);
TextView phoneNumDisplay = findViewById(R.id.phoneTxt);
TextView emailDisplay = findViewById(R.id.emailTxt);
TextView accBalDisplay = findViewById(R.id.accBal);
firstNameDisplay.setText("First");
lastNameDisplay.setText("Last");
phoneNumDisplay.setText("Phone");
emailDisplay.setText("Email");
accBalDisplay.setText("Balance");
final Button newUserButton = findViewById(R.id.newUserButton);
newUserButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//this is for inputs on a separate page
setContentView(R.layout.layout2);
final TextView lastName = findViewById(R.id.lastName);
final TextView firstName = findViewById(R.id.firstName);
final TextView phoneNumber = findViewById(R.id.phoneNumber);
final TextView email = findViewById(R.id.emailAddress);
final TextView accountBalance = findViewById(R.id.accountAmount);
Button submitBtn = findViewById(R.id.submitBtn);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.activity_main);
//These are the textboxes in the table
TextView fName = findViewById(R.id.fName);
TextView lName = findViewById(R.id.lName);
TextView phone = findViewById(R.id.phone);
TextView emailAdd = findViewById(R.id.email);
TextView balance = findViewById(R.id.Balance);
fName.setText(firstName + "");
lName.setText(lastName + "");
phone.setText(phoneNumber + "");
emailAdd.setText(email + "");
balance.setText(accountBalance + "");
}
});
}
});
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
[1]: https://i.stack.imgur.com/8CfWD.png
In this line of your code:
fName.setText(firstName + "");
the variable firstName is actually a TextView, so the compiler will implicitly call firstName.toString() which will give you the string that you see (it will NOT give you the text in the TextView). The line should probably be:
fName.setText(firstName.getText());
Ditto for the other places where you use the TextView + "" pattern (which I would discourage from using for any reason).
Related
I want the user to have the same radio button checked which he had
previously checked before the app was closed.
This is my source code
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.R;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
textView = findViewById(R.id.text_view_selected);
Button buttonApply = findViewById(R.id.button_apply);
buttonApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
textView.setText("Your choice: " + radioButton.getText());
}
});
}
public void checkButton(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
Toast.makeText(this, "Selected Radio Button: " + radioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
I want the radio button states to be saved for next time the app is
used.
You should take a look at sharedPreferences : https://developer.android.com/training/data-storage/shared-preferences
Save your data :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("myRadio", radioButton.getText());
editor.commit();
Retrieve data :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String defaultValue = "";
String radioButtonText = sharedPref.getString("myRadio", defaultValue);
For now, you can do this :
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
TextView textView;
// Declare SharedPreferences as attributes
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
textView = findViewById(R.id.text_view_selected);
// Retrieve SharedPreferences
sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPref.edit();
Button buttonApply = findViewById(R.id.button_apply);
buttonApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
textView.setText("Your choice: " + radioButton.getText());
}
});
}
#Override
protected void onResume() {
int radioIdChecked = -1;
radioIdChecked = sharedPref.getInt("myRadioChecked", radioIdChecked);
if (radioIdChecked == -1) {
// ERROR, don't check anything
Log.d("TAG", "error: don't check anything");
}
else {
RadioButton radioButton = radioGroup.findViewById(radioIdChecked);
if (radioButton != null) {
radioButton.setChecked(true);
}
}
}
#Override
protected void onPause() {
editor.putInt("myRadioChecked", radioGroup.getCheckedRadioButtonId());
editor.commit();
}
Best
Means I want to sort my firebaserecycleradapter according to highest no of ratings first after applying query on data having title with value "vikas"
This is my code:
package com.onlinetuto;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.onlinetuto.model.blog;
import static com.onlinetuto.EmptyActivity.EXTRA_POST_KEY;
public class GetLocation extends AppCompatActivity {
private static final String TAG = "MainActivity";
private RecyclerView re;
private DatabaseReference d,dref;
private FirebaseAuth mauth;
FirebaseRecyclerAdapter<blog,BlogViewholder> firebaseRecyclerAdapter;
DatabaseReference users, comments;
ProgressBar progressBar;
String locname;
SharedPreferences sharedPreferences;
LinearLayoutManager linearLayoutManager;
AutoCompleteTextView autoCompleteTextView;
Intent intent;
Button button;
Long code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location);
intent=getIntent();
if(intent!=null)
{
code= intent.getLongExtra("queryname",110094);
}
Toast.makeText(this, code.toString(), Toast.LENGTH_SHORT).show();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mauth = FirebaseAuth.getInstance();
d = FirebaseDatabase.getInstance().getReference().child("Products");
users = FirebaseDatabase.getInstance().getReference().child("Users");
comments = FirebaseDatabase.getInstance().getReference().child("post-comments");
Query nm=d.orderByChild("pincode").equalTo(code);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
// mquery = dtop.orderByChild("title").equalTo("hul");
// mquery2 = dtop.orderByChild("likeCount").limitToFirst(100);
//for offline capabilities of database
// d3.keepSynced(true);
d.keepSynced(true);
// mdatabaselike.keepSynced(true);
re = (RecyclerView) findViewById(R.id.blog_list);
re.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
re.setLayoutManager(linearLayoutManager);
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<blog, BlogViewholder>(
blog.class,
R.layout.blog_row,
BlogViewholder.class,
nm
) {
#Override
protected void populateViewHolder(final BlogViewholder viewHolder, final blog model, int position) {
final String post_key = getRef(position).getKey();
//for retrieving each post key getRef() method is used for this.
final DatabaseReference post_ref = getRef(position);
viewHolder.setTitle(model.getClassname());
viewHolder.setImage(getApplicationContext(), model.getImageone());
viewHolder.setReviews(model.getReviews());
viewHolder.setTypo(model.getType());
viewHolder.setNoofComments(model.getNoofreviews());
viewHolder.setratings(model.getNetrat());
viewHolder.setTextRating(model.getNoofreviews());
viewHolder.vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newIntent = new Intent(GetLocation.this, EmptyActivity.class);
newIntent.putExtra(EXTRA_POST_KEY, post_key);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(newIntent);
}
});
progressBar.setVisibility(View.GONE);
}
};
re.setAdapter(firebaseRecyclerAdapter);
}
private Boolean exit = false;
#Override
public void onBackPressed() {
if (exit) {
finish(); // finish activity
} else {
Toast toast=Toast.makeText(this, "Press Back again to exit", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(getResources().getColor(R.color.toa));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(getResources().getColor(R.color.blackm));
/*Here you can do anything with above textview like text.setTextColor(Color.parseColor("#000000"));*/
toast.show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 2 * 1000);
}
}
public static class BlogViewholder extends RecyclerView.ViewHolder {
View vi;
FirebaseAuth mauth;
EditText e1;
public BlogViewholder(View itemView) {
super(itemView);
vi = itemView;
mauth = FirebaseAuth.getInstance();
}
/* public void setImage(Context context,String image){
ImageView imageView=(ImageView)vi.findViewById(R.id.post_iamge);
Picasso.with(context).load(image).into(imageView);
}*/
public void setTitle(String classname) {
TextView textView = (TextView) vi.findViewById(R.id.textViewTitle);
textView.setText(classname);
}
public void setImage(Context context, String image){
ImageView imageView=(ImageView)vi.findViewById(R.id.imageView);
Glide.with(context).load(image).into(imageView);
}
public void setReviews(String reviews) {
TextView textView = (TextView) vi.findViewById(R.id.reviews);
textView.setText(reviews);
}
public void setTypo(String type) {
TextView textView = (TextView) vi.findViewById(R.id.type);
textView.setText(type);
}
public void setTextRating(long comme) {
TextView textView = (TextView) vi.findViewById(R.id.textViewRating);
textView.setText(comme + "");
}
public void setNoofComments(long comme) {
TextView textView = (TextView) vi.findViewById(R.id.reviews);
textView.setText(comme+" Reviews");
}
public void setratings(Long rat) {
RatingBar textView = (RatingBar) vi.findViewById(R.id.img);
Integer myNum=0;
if(rat==null)
myNum=0;
else
{
Integer integer=(int)(long)rat;
myNum=integer;
}
if(myNum>5)
{
myNum=myNum%5;
textView.setRating(myNum);
}
else
{
textView.setRating(myNum);
}
}
}
}
this is my code please help me.i want to sort query data according to their ratings before passing it to the firebase recycleradapter .how can i acheive that?
Product database reference one key data:-
i am using firebase realtime database here
I'm using this one to sort it by latest post.
#Override
public blog getItem(int position) {
return super.getItem(getItemCount() - (position + 1));
}
I was trying to program a simple calculator in Android Studio, only with plus, minus, times and divide functions. I am half-code in programming of "plus" function, which is triggered by clicking a button. Here is my code in MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public class Arithmetic {
public void plus(View view) {
EditText editText = (EditText) findViewById(R.id.editText);
EditText editText2 = (EditText) findViewById(R.id.editText2);
TextView textView = (TextView) findViewById(R.id.textView);
String numberOne = editText.getText().toString();
String numberTwo = editText2.getText().toString();
String result = numberOne + numberTwo;
}
}}
Now I have two questions. Firstly, how do I make it to show result in textView? Secondly, public void plus is not showing in button's box onClick. Why? And how do I make it to show there?
I will be really thankful for every useful tip.
1.Firstly, how do I make it to show result in textView
int sum = (Integer.parseInt(numberOne)) + (Integer.parseInt(numberTwo));
String result = sum + "";
textView.setText(result);
//or
textView.setText(sum + "");
2.Why public void plus is not showing in button's box onClick
<button
----
android:onClick = "plus"/>
and
public class MainActivity extends AppCompatActivity{
onCreate().....
public void plus(View view){
//your button code here
}
No need to create a nested class for that!
This is what you are looking for, but you should learn some Android and Java basics before starting a project:
Remove the onClick property of your button in your xml file, it's better to use a OnClickListener (particularly if you are planning to use multiple buttons)
package com.example.arnaudpradier.calculator;
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.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button calculBtn;
EditText inputFieldOne;
EditText inputFieldTwo;
TextView showResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calculBtn = (Button) findViewById(R.id.calculateBtn);
inputFieldOne = (EditText) findViewById(R.id.inputFieldOne);
inputFieldTwo = (EditText) findViewById(R.id.inputFieldTwo);
showResult = (TextView) findViewById(R.id.resultText);
calculBtn.setOnClickListener(this);
}
private void makeAddition() {
int firstValue = (Integer.parseInt(inputFieldOne.getText().toString()));
int secondValue = (Integer.parseInt(inputFieldTwo.getText().toString()));
String result = (firstValue + secondValue) + "";
showResult.setText(result);
}
#Override
public void onClick(View view) {
int i = view.getId();
if (i == R.id.calculateBtn) {
makeAddition();
}
}
}
public class MainActivity extends AppCompatActivity {
EditText editText;
EditText editText2;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
textView = (TextView) findViewById(R.id.textView);
Arithmetic a = new Arithmetic();
Arithmetic.plus();
}
public class Arithmetic {
public void plus() {
String numberOne = editText.getText().toString();
String numberTwo = editText2.getText().toString();
String result = numberOne + numberTwo;
textView.setText(result);
}
}}
[Android newbie] Help required in adding 4 math operations as options to a radion button.
Also I need to perform respective options on selecting radio button option.
package com.sivaneshsg.wallet;
import android.support.annotation.IdRes;
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.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
int cashamount = 0;
int cardamount = 0;
int walletamount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et = (EditText) findViewById(R.id.inputamount);
final RadioButton card1 = (RadioButton) findViewById(R.id.card1);
final RadioButton cash1 = (RadioButton) findViewById(R.id.cash1);
final RadioButton card2 = (RadioButton) findViewById(R.id.card2);
final RadioButton cash2 = (RadioButton) findViewById(R.id.cash2);
final RadioGroup rg =(RadioGroup) findViewById(R.id.rgroup);
final TextView t1 = (TextView) findViewById(R.id.amountcard);
final TextView t2 = (TextView) findViewById(R.id.amountcash);
final TextView t3 = (TextView) findViewById(R.id.amountwallet);
Button but = (Button) findViewById(R.id.button);
final int amount = Integer.parseInt(et.getText().toString());
cash1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash2.setChecked(false);
card1.setChecked(false);
card2.setChecked(false);
cashamount = cashamount + amount;
}
});
card1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash2.setChecked(false);
cash1.setChecked(false);
card2.setChecked(false);
cardamount=cardamount+amount;
}
});
cash2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash1.setChecked(false);
card1.setChecked(false);
card2.setChecked(false);
cashamount = cashamount - amount;
}
});
card2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash2.setChecked(false);
cash1.setChecked(false);
card2.setChecked(false);
cardamount=cardamount-amount;
}
});
but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
t1.setText("Amount in Card : RS. " + cardamount);
t2.setText("Amount in Cash : Rs. " + cashamount);
walletamount = cardamount + cashamount;
t3.setText("Total Amount in Wallet : RS. " + walletamount);
}
});
}
}
your amount variable taking value at onCreate() method which is initially 0
I'm not sure what's wrong here, all i want to do is randomly grab an item from my array. Which is just like a random sentence. Then generate another once the button is pressed. All my code looks good to me but it's causing a crash when i hit the button. any ideas?
package com.my.package;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View.OnClickListener;
public class Randomsentence extends Activity implements OnClickListener{
private String[] myString;
private static final Random rgenerator = new Random();
private TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
TextView tv = (TextView) findViewById(R.id.text1);
tv.setText(q);
View nextButton = findViewById(R.id.next_button);
nextButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next_button:
tv.setText(myString[rgenerator.nextInt(myString.length)]);
break;
}
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu3, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id.menu:
startActivity(new Intent(this, Main.class));
return true;
case R.id.startnhie:
startActivity(new Intent(this, startnhie.class));
return true;
}
return false;
}
}
In your onCreate(), change
TextView tv = (TextView) findViewById(R.id.text1);
to
tv = (TextView) findViewById(R.id.text1);
since you already declared TextView tv as an instance variable.