Unfortunately (My App) Has Stopped Working - java

Okay, this happened when I created a simple ImageButton. I don't see what I'm doing wrong though... Here's my code:
(My Activity.Xml File):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/tapbgh"
android:orientation="vertical" >
<TextView
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="#string/level01"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/Score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="#string/click0"
android:textColor="#FFFFFF"
android:textSize="16pt" />
<Chronometer
android:id="#+id/Timer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center_horizontal"
android:text="01:00"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/Tap"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.81"
android:background="#drawable/buttonbg" />
<Button
android:id="#+id/Menu"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Menu" />
<ImageButton
android:id="#+id/Reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/resetbtn"
android:src="#drawable/resetbtn" />
</LinearLayout>
(My .Java File):
package my.first.app;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.Button;
//Click Events Below This Line
public class Tap_Game_Activity extends Activity {
private Button tapBtn;
private Button rstBtn;
int scr = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Menu = (Button) findViewById(R.id.Menu);
registerForContextMenu(Menu);
tapBtn = (Button) findViewById(R.id.Tap);
rstBtn = (Button) findViewById(R.id.Reset);
rstBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView Score = (TextView) findViewById(R.id.Score);
Score.setText("0");
scr = 0;
}
});
tapBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scr = scr + 1;
TextView Score = (TextView) findViewById(R.id.Score);
Score.setText(String.valueOf(scr));
}
});
}
// Options Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderTitle("Menu");
menu.add(0, view.getId(), 0, "Resume");
menu.add(0, view.getId(), 0, "Quit");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Invoke Context Function 1") {
contextFunction1(item.getItemId());
}
else if(item.getTitle()=="Invoke Context Function 2") {
contextFunction2(item.getItemId());
}
else {
return false;
}
return true;
}
public void contextFunction1(int id){
Toast.makeText(this, "function 1 invoked!", Toast.LENGTH_SHORT).show();
}
public void contextFunction2(int id){
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Tap_Game_Activity.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
I feel like it may be in this line:
rstBtn = (Button) findViewById(R.id.Reset);
But I still don't understand, any help would be great, thank you.

API tells me, that we can't cast ImageButton to Button. Try to declare rstBtn as an ImageButton and adjust the cast.

rstBtn = (Button) findViewById(R.id.Reset);
You are casting ImageButton to Button when ImageButton does not inherit from Button.
http://developer.android.com/reference/android/widget/ImageButton.html
BTW: Please choose a title that better describes your problem and include every error messages you get in your question.

private ImageButton rstBtn;
....
rstBtn = (ImageButton) findViewById(R.id.Reset);
rstBtn.setOnClickListener(........

Related

The application has stopped unexpectedly. please try again "Force close" error in my android codes

I wrote below codes for Android in Eclipse:
package mohammad.negahdari.mystartup4;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MyStartup4Activity extends Activity {
public int counter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtCaption = (TextView) findViewById(R.id.txtCaption);
final Button btn1 = (Button) findViewById(R.id.txtCaption);
txtCaption.setText("Hooora");
txtCaption.setTextColor(Color.parseColor("#0000ff"));
txtCaption.setBackgroundColor(Color.parseColor("#ffffff"));
for (int i = 0; i <= 4; i++)
Toast.makeText(MyStartup4Activity.this, "Mohammad " + i, Toast.LENGTH_SHORT).show();
txtCaption.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("LOG", "Clicked");
Toast.makeText(MyStartup4Activity.this, "Clicked", Toast.LENGTH_SHORT).show();
counter++;
txtCaption.setText("Number is : " + counter);
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("LOG", "Clicked");
Toast.makeText(MyStartup4Activity.this, "Clicked", Toast.LENGTH_SHORT).show();
txtCaption.setVisibility(View.GONE);
}
});
}
}
and receive this error:
The application has stopped unexpectedly. please try again
But when I delete these lines:
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("LOG", "Clicked");
Toast.makeText(MyStartup4Activity.this, "Clicked", Toast.LENGTH_SHORT).show();
txtCaption.setVisibility(View.GONE);
}
});
I have no error.
My xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtCaption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff00ff"
android:gravity="center"
android:text="..."
android:textColor="#00ff00"
android:textSize="40dip" />
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
The application has stopped unexpectedly. please try again But when I
delete these lines: have no error.
Obviously,you are referring to the wrong id
final TextView txtCaption = (TextView) findViewById(R.id.txtCaption);
final Button btn1 = (Button) findViewById(R.id.txtCaption);
Check your button id in xml. You should assign different id to your button.
In your case, you should use
final Button btn1 = (Button) findViewById(R.id.btn1);
final TextView txtCaption = (TextView) findViewById(R.id.txtCaption);
final Button btn1 = (Button) findViewById(R.id.txtCaption);
Both txtCaption and btn1 point to the same id (R.id.txtCaption)
My xml codes :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtCaption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff00ff"
android:gravity="center"
android:text="..."
android:textColor="#00ff00"
android:textSize="40dip" />
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>

App seems like launching more than once in landscape mode after splash screen?

I have a splash screen and after that my main activity starts. This works fine in portrait mode but if in case i tilt my phone in landscape mode, the main activity can be seen launching more than once after splash screen.
I tried using android:launchMode="singleInstance" but in that case i am not able to attach files in feedback alert-box.
Following is my code:
MainActivity.java
package com.example.android.tel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
TextView toolbar_title_mainActivity, main_textView, disclaimer_txtView;
CardView SearchDept, SearchName, disclaimer, feedback;
ImageView back;
ArrayList<Uri> arrayUri = new ArrayList<Uri>();
ArrayAdapter<Uri> myFileListAdapter;
ListView listViewFiles;
Dialog alertDialog;
final int RQS_LOADIMAGE = 0;
final int RQS_SENDEMAIL = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_main);
}
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar_main_activity);
toolbar_title_mainActivity = (TextView) findViewById(R.id.toolbar_title);
main_textView = (TextView) findViewById(R.id.main_textView);
main_textView.setPaintFlags(main_textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_mainActivity.setText("Hry. Govt. Telephone Directory");
back = (ImageView) findViewById(R.id.back);
back.setVisibility(View.INVISIBLE);
disclaimer = (CardView) findViewById(R.id.disclaimer);
feedback = (CardView) findViewById(R.id.feedback);
SearchDept = (CardView) findViewById(R.id.cardView1_mainActivity);
SearchName = (CardView) findViewById(R.id.cardView2_mainActivity);
SearchDept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CardViewActivity.class);
startActivity(i);
}
});
SearchName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, ByNameListActivity.class);
startActivity(j);
}
});
disclaimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.disclaimer);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.show();
}
});
feedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.feedback);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.setCanceledOnTouchOutside(true);
ImageView send_btn=(ImageView)alertDialog.findViewById(R.id.send);
ImageView attach_btn=(ImageView)alertDialog.findViewById(R.id.attachment);
final TextView to_email_add=(TextView)alertDialog.findViewById(R.id.email_address);
to_email_add.setText("tel#gmail.com");
final EditText email_subject=(EditText)alertDialog.findViewById(R.id.email_subject);
final EditText email_text=(EditText)alertDialog.findViewById(R.id.email_text);
final EditText mobile_no=(EditText)alertDialog.findViewById(R.id.mobile_text);
email_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
email_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
myFileListAdapter = new ArrayAdapter<Uri>(
MainActivity.this,
android.R.layout.simple_list_item_1,
arrayUri);
listViewFiles = (ListView)alertDialog.findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
listViewFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
myFileListAdapter.remove(arrayUri.get(position));
myFileListAdapter.notifyDataSetChanged();
Toast.makeText(view.getContext(), "You unattached one item", Toast.LENGTH_LONG).show();
return false;
}
});
attach_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_add=to_email_add.getText().toString();
String email_sub=email_subject.getText().toString();
String email_txt=email_text.getText().toString();
String emailAddressList[] = {email_add};
String mobileNo=mobile_no.getText().toString();
String info=email_txt+"\n\nPhone Number :"+mobileNo;
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);
intent.putExtra(Intent.EXTRA_SUBJECT, email_sub);
intent.putExtra(Intent.EXTRA_TEXT,info);
if(arrayUri.isEmpty()&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email without photo attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size() == 1 && isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with ONE photo attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size()>1&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with MULTI photo attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}
else {
Toast.makeText(v.getContext(), "Phone number is not valid", Toast.LENGTH_LONG).show();
}
startActivity(Intent.createChooser(intent, "Please provide valid details"));
}
});
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
arrayUri.add(imageUri);
myFileListAdapter.notifyDataSetChanged();
break;
case RQS_SENDEMAIL:
break;
}
}
}
public static boolean isValidPhone(String phone)
{
String expression = "^([0-9\\+]|\\(\\d{1,3}\\))[0-9\\-\\. ]{3,15}$";
CharSequence inputString = phone;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:weightSum="14"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
tools:context="com.example.android.tel.MainActivity">
<include
android:id="#+id/tool_bar_main_activity"
layout="#layout/toolbar">
</include>
<TextView
android:id="#+id/main_textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
android:text="How would you like to search?"
android:textStyle="bold"
android:textSize="14sp"
android:textColor="#1A237E"
android:gravity="center_horizontal"/>
<RelativeLayout
android:id="#+id/searchby_btns"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="4"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView1_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Department.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView2_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_below="#id/cardView1_mainActivity"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="20dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Name.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="8.5">
<ImageView
android:id="#+id/map_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/hry_map"
android:elevation="4dp"
android:layout_gravity="center"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/map_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
android:id="#+id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
android:layout_marginRight="8dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Disclaimer"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/feedback"
android:layout_toRightOf="#id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Feedback"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
</LinearLayout>
SplashScreenActivity.java
package com.example.android.telephonedirectory;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import com.felipecsl.gifimageview.library.GifImageView;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class SplashScreenActivity extends AppCompatActivity {
// private GifImageView gifimageview;
private ProgressBar progressBarSplashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_splash_screen);
} else {
setContentView(R.layout.activity_splash_screen);
}
// gifimageview=(GifImageView)findViewById(R.id.gifSplashscreenImage);
progressBarSplashScreen=(ProgressBar)findViewById(R.id.progressbarSplashscreen);
progressBarSplashScreen.setVisibility(progressBarSplashScreen.VISIBLE);
//set GifImageView Resource
/*try {
InputStream inputStream=getAssets().open("splash_Screen.png");
byte[] bytes= IOUtils.toByteArray(inputStream);
gifimageview.setBytes(bytes);
gifimageview.startAnimation();
}catch (IOException ex){
}*/
//Wait for 4 seconds and start activity main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SplashScreenActivity.this.startActivity(new Intent(SplashScreenActivity.this,MainActivity.class));
SplashScreenActivity.this.finish();
}
},2000);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
Dont use android:launchMode="singleInstance"
Launch mode you should use "singleTask" for this .
Because singleInstance creates separate task stack for Activity and do not check activity in current Task Stack.
while "singleTask" check each time if an Activity exist in Task Stack it can not create new one.

Why can't button display score on the screen?

I am trying create a simple quiz app where depending from user choices in checkBoxes, submitButton displays the result on the screen. When answer is right score increase 1 point, if answer is wrong score decrease 1 point.
I am totaly stuck!
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int score;
Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitButton = (Button) findViewById(R.id.submitAnswer);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitButton.setText(score);
}
});
}
public void checkBoxes(View view) {
CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
boolean hasCheckBox1 = checkBox1.isChecked();
CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
boolean hasCheckBox2 = checkBox2.isChecked();
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()){
case R.id.checkBox1:
Toast.makeText(this, "Hooray!Your answer is right", Toast.LENGTH_SHORT).show();
score ++;
break;
case R.id.checkBox2:
Toast.makeText(this,"Sorry, try again!", Toast.LENGTH_SHORT).show();
score --;
break;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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.allyouask.practicebutton.MainActivity">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RightAnswer"
android:id="#+id/checkBox1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="179dp"
android:onClick="checkBoxes"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WrongAswer"
android:id="#+id/checkBox2"
android:layout_below="#+id/checkBox1"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:onClick="checkBoxes"/>
<Button
android:id="#+id/submitAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="20sp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="onClick"/>
</RelativeLayout>
Your score in int type, you use setText(int) in this case. So you're trying to load resource with id==score.
Try to modify arguments, to use this version of the setText method:
submitButton.setText(String.valueOf(score))
you have to call an update method in order to update text on the Button or update its content other way, like this below
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int score;
Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitButton = (Button) findViewById(R.id.submitAnswer);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitButton.setText(String.valueOf(score));
}
});
}
public void checkBoxes(View view) {
CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
boolean hasCheckBox1 = checkBox1.isChecked();
CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
boolean hasCheckBox2 = checkBox2.isChecked();
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()){
case R.id.checkBox1:
Toast.makeText(this, "Hooray!Your answer is right", Toast.LENGTH_SHORT).show();
score ++;
break;
case R.id.checkBox2:
Toast.makeText(this,"Sorry, try again!", Toast.LENGTH_SHORT).show();
score --;
break;
}
//submitButton.setText(String.valueOf(score));
}
}
try this --> Replace int score; line your code with int score = 0; and check if it works.
you should use:
private int score=0

How to move a setText() to a new activity on Android Studio?

I am tying to make a basket and want depending on what button is pressed the price that is shown on the screen then appear in the basket (new activity) in TextView09 ( section of the table) but at the moment what is appearing is android.support.v7.widget.App...
Here is the activity page for the product:
package com.example.emily.woodensigns;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.LayoutInflater;
public class Letters extends AppCompatActivity {
int txtSize = 14;
EditText Wood;
Button bSize, bSize1, bSize2, bSize3, bBasket;
public int count = 5;
private LayoutInflater mInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_letters);
Wood = (EditText) findViewById(R.id.Wood);
Button bSize = (Button) findViewById(R.id.bSize);
Button bSize1 = (Button) findViewById(R.id.bSize1);
Button bSize2 = (Button) findViewById(R.id.bSize2);
Button bSize3 = (Button) findViewById(R.id.bSize3);
Button bBasket = (Button) findViewById(R.id.bBasket);
final TextView price = (TextView) findViewById(R.id.price);
bSize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wood.setTextSize(40);
price.setText("£10");
TextView price = (TextView) findViewById(R.id.price);
String pri = price.getText().toString();
Intent intent2 = new Intent(Letters.this, Letters.class);
intent2.putExtra("£",pri);
}
});
bSize1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wood.setTextSize(60);
price.setText("£20");
}
});
bSize2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wood.setTextSize(100);
price.setText("£35");
}
});
bSize3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wood.setTextSize(150);
price.setText("£50");
}
});
bBasket.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Wood = (EditText) findViewById(R.id.Wood);
String str = Wood.getText().toString();
if (str.length() == 0) {
Wood.requestFocus();
Wood.setError("FIELD CANNOT BE EMPTY");
} else if (str.length() >= 2) {
Wood.requestFocus();
Wood.setError("You can only type one letter!");
} else {
Intent intent2 = new Intent(Letters.this, Basket.class);
intent2.putExtra("MY_INFO",str + " - Letters" + price );
startActivity(intent2);
}
}
});
}
}
Activity for the Basket:
package com.example.emily.woodensigns;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
public class Basket extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_basket);
TextView TextView08 = (TextView) findViewById(R.id.TextView08);
TextView TextView09 = (TextView) findViewById(R.id.TextView09);
Button bCheckout=(Button) findViewById(R.id.bCheckout);
String strFromActivity = getIntent().getStringExtra("MY_INFO");
TextView08.setText(strFromActivity);
String priFromActivity = getIntent().getStringExtra("£" );
TextView09.setText(priFromActivity);
Toast.makeText(getBaseContext(),priFromActivity, Toast.LENGTH_LONG).show();
bCheckout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent2 = new Intent(Basket.this, customerDetails.class);
startActivity(intent2);
}
});
}
}
Basket xml file:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="259dp"
android:shrinkColumns="*" android:stretchColumns="*" android:background="#ffffff">
<!-- Row 1 with single column -->
<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:text=""
android:layout_span="3"
android:padding="18dip"
android:background="#b0b0b0"
android:textColor="#000"/>
</TableRow>
<!-- Row 2 with 3 columns -->
<TableRow
android:id="#+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="#+id/TextView04"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="left"/>
<TextView
android:id="#+id/TextView05"
android:text="Product"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
<TextView
android:id="#+id/TextView06"
android:text="Price"
android:layout_weight="1"
android:background="#d3d3d3"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
</TableRow>
<TableRow>
<TextView
android:id="#+id/TextView07"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="left"/>
<TextView
android:id="#+id/TextView08"
android:text="Product"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
<TextView
android:id="#+id/TextView09"
android:text="Price"
android:layout_weight="1"
android:background="#d3d3d3"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
</TableRow>
</TableLayout>
thank you
Your btn click code should like below:
bBasket.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Wood = (EditText) findViewById(R.id.Wood);
String str = Wood.getText().toString();
if (str.length() == 0) {
Wood.requestFocus();
Wood.setError("FIELD CANNOT BE EMPTY");
} else if (str.length() >= 2) {
Wood.requestFocus();
Wood.setError("You can only type one letter!");
} else {
Intent intent2 = new Intent(Letters.this, Basket.class);
intent2.putExtra("MY_INFO",str + " - Letters" + price );
TextView price = (TextView) findViewById(R.id.price);
String pri = price.getText().toString();
intent2.putExtra("£",pri);
startActivity(intent2);
}
}
});
Hope this will help you.

Integer value in TextView won't update; onClickListener won't run code

No matter how much I edit or change to my Java code for this assignment, it refused to properly update the value of the integer variable I've set for the result. Can someone show me what on earth I'm missing here? Below is my code:
package com.example.minicalc;
import com.example.minicalc.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class MainActivity extends Activity implements OnEditorActionListener {
private static final String TAG = "MiniCalc";
private SharedPreferences savedValues;
private EditText editText1;
private EditText editText2;
private Button button1;
private Spinner spinner1;
private TextView answerLbl;
private int ivalue1 = 0;
private int ivalue2 = 0;
private int ianswer;
private int spinChoice;
//private String[] spinner_strings = {"+", "-", "×", "÷"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate event started");
setContentView(R.layout.activity_main);
spinner1 = (Spinner) findViewById(R.id.spinner1);
button1 = (Button) findViewById(R.id.button1);
answerLbl = (TextView) findViewById(R.id.answerTxt);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText1.setOnEditorActionListener(this);
editText2.setOnEditorActionListener(this);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
spinChoice = spinner1.getSelectedItemPosition();
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.d(TAG, "onClick event started");
ianswer = 0;
if (spinChoice == 0) {
ianswer = ivalue1 + ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 1) {
ianswer = ivalue1 - ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 2) {
ianswer = ivalue1 * ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 3) {
ianswer = ivalue1 / ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
}
answerLbl.setText(Integer.toString(ianswer));
//answerLbl.setText(""+ianswer);
Log.d(TAG, "answerLbl TEXT IS: " + answerLbl.getText());
}
});
}
#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);
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.d(TAG, "onEditorAction event started");
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
ivalue1 = Integer.parseInt(editText1.getText().toString());
ivalue2 = Integer.parseInt(editText2.getText().toString());
}
return false;
}
#Override
public void onPause() {
Log.d(TAG, "onPause event started");
Editor editor = savedValues.edit();
editor.putString("value1", editText1.getText().toString());
editor.putString("value2", editText2.getText().toString());
editor.commit();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume event started");
editText1.setText(savedValues.getString("value1", ""));
editText2.setText(savedValues.getString("value2", ""));
}
}
Here is my layout XML, activity_main.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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.minicalc.MainActivity" >
<TextView
android:id="#+id/valLbl1"
android:labelFor="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="40dp"
android:text="#string/valueLbl1" />
<TextView
android:id="#+id/valLbl2"
android:labelFor="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl1"
android:layout_below="#+id/editText1"
android:layout_marginTop="24dp"
android:text="#string/valueLbl2" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl1"
android:layout_below="#+id/valLbl1"
android:layout_marginTop="20dp"
android:ems="5"
android:inputType="number">
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl2"
android:layout_below="#+id/valLbl2"
android:layout_marginTop="16dp"
android:ems="5"
android:inputType="number" />
<TextView
android:id="#+id/answerTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/answerLblTxt"
android:layout_centerHorizontal="true"
android:ems="7"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="#string/submit" />
<TextView
android:id="#+id/answerLblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/editText2"
android:layout_below="#+id/button1"
android:layout_marginTop="16dp"
android:text="#string/answerLbl" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/valLbl2"
android:layout_marginStart="28dp"
android:layout_toEndOf="#+id/editText2"
android:entries="#array/spinner_strings" />
</RelativeLayout>
Now, the app runs fine, the LogCat messages show up fine...except when I put them in the onClickListener. So yes, I've sorta identified WHERE the problem is, I just don't know WHAT the problem is. I'd show a screen shot of the error, but this is my first time posting. In any case, the phone I'm running the app on is a Samsung Galaxy Note 3, running Android 4.4.4. Can anyone help me?
Your spinners getSelectedItemPoisition() method is only called once in your onCreate() method and it is not called every time you click on the button, resulting in the value never being updated.
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
spinChoice = spinner1.getSelectedItemPosition();
...
}
This line of code needs to be added in the onClick() method causing the new value to be read on button click.

Categories

Resources