My application shut down unexpectedly, I don't really know what the problem is. I'm new to programming java. I tried the 'try', 'catch' and 'finally' methods.
Here is the code:
package com.eqsec.csaba;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class EqsecActivity extends Activity {
/** Called when the activity is first created. */
Button solve;
EditText vA, vB, vC;
TextView solution;
int discriminant, iA, iB, iC;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
solve = (Button) findViewById(R.id.bSolve);
vA = (EditText) findViewById(R.id.etA);
vB = (EditText) findViewById(R.id.etB);
vC = (EditText) findViewById(R.id.etC);
solve.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try{
String A = vA.getText().toString();
iA = Integer.parseInt(A);
String B = vB.getText().toString();
iB = Integer.parseInt(B);
String C = vC.getText().toString();
iC = Integer.parseInt(C);
solution.setText("Yout total is " + iA);
}catch (ArithmeticException e) {
e.printStackTrace();
}
}
});
}
}
Please help me, i want to write an android application, which can solve some math problems.
You have to catch NumberFormatException instead of ArithmeticException.
And initialize solution variable before. Like:
solution = (TextView) findViewById(R.id.solution);
Full code will be:
package com.eqsec.csaba;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class EqsecActivity extends Activity {
/** Called when the activity is first created. */
Button solve;
EditText vA, vB, vC;
TextView solution;
int discriminant, iA, iB, iC;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
solve = (Button) findViewById(R.id.bSolve);
vA = (EditText) findViewById(R.id.etA);
vB = (EditText) findViewById(R.id.etB);
vC = (EditText) findViewById(R.id.etC);
solution = (TextView) findViewById(R.id.solution);
solve.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try{
String A = vA.getText().toString();
iA = Integer.parseInt(A);
String B = vB.getText().toString();
iB = Integer.parseInt(B);
String C = vC.getText().toString();
iC = Integer.parseInt(C);
solution.setText("Yout total is " + iA);
}catch (NumberFormatException e) {
e.printStackTrace();
}
}
});
}
}
Try this:
solve.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String A = vA.getText().toString();
iA = Integer.ValueOf(A);
String B = vB.getText().toString();
iB = Integer.ValueOf(B);
String C = vC.getText().toString();
iC = Integer.ValueOf(C);
// intialize solution
solution.setText("Yout total is " + String.ValueOf(iA));
//This is not the total yet
}
});
Related
I am working on a side project in android studio and need to store some long term data to a file that can be written and readable, I am able to do this outside of android studio, but when I try to do it within, it sows a error saying
public void onClick(View v) 'onClick(View)' in 'Anonymous class derived from android.view.View.OnClickListener' clashes with 'onClick(View)' in 'android.view.View.OnClickListener'; overridden method does not throw 'java.io.FileNotFoundException'{
I have a function in a separate file that writes to a string from a file, but when I try to access that string from one of my main view pages, its asking for an exception, but will not work with said exception, I've tried try and catch but with no success
File being initialized and written:
package com.example.stellarisspeciesrandomizer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class DLCPage extends AppCompatActivity {
public static int[] DLCArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.dlc_page);
try {
File myObj = new File("hasDLC.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
DLCArray = new int[1];
Button doneButton = (Button) findViewById(R.id.button_done);
doneButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws IOException {
writeToFile();
finish();
}});
ImageButton aquaticsCheckbox = (ImageButton) findViewById(R.id.aquatic_checkbox);
aquaticsCheckbox.setTag("1");
//hello
aquaticsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (aquaticsCheckbox.getTag() == "1") {
aquaticsCheckbox.setImageResource(R.drawable.checked);
aquaticsCheckbox.setTag("2");
DLCArray[0] = 1;
} else if (aquaticsCheckbox.getTag() == "2") {
aquaticsCheckbox.setImageResource(R.drawable.checkmark);
aquaticsCheckbox.setTag("1");
DLCArray[0] = 0;
}
}
});
ImageButton humanoidCheckbox = (ImageButton) findViewById(R.id.humanoid_checkbox);
humanoidCheckbox.setTag("1");
humanoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (humanoidCheckbox.getTag() == "1") {
humanoidCheckbox.setImageResource(R.drawable.checked);
humanoidCheckbox.setTag("2");
DLCArray[1] = 1;
} else if (humanoidCheckbox.getTag() == "2") {
humanoidCheckbox.setImageResource(R.drawable.checkmark);
humanoidCheckbox.setTag("1");
DLCArray[1] = 0;
}
}
});
ImageButton plantoidCheckbox = (ImageButton) findViewById(R.id.plantoid_checkbox);
plantoidCheckbox.setTag("1");
plantoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (plantoidCheckbox.getTag() == "1") {
plantoidCheckbox.setImageResource(R.drawable.checked);
plantoidCheckbox.setTag("2");
DLCArray[2] = 1;
} else if (plantoidCheckbox.getTag() == "2") {
plantoidCheckbox.setImageResource(R.drawable.checkmark);
plantoidCheckbox.setTag("1");
DLCArray[2] = 0;
}
}
});
ImageButton syntheticCheckbox = (ImageButton) findViewById(R.id.synthetic_checkbox);
syntheticCheckbox.setTag("1");
syntheticCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (syntheticCheckbox.getTag() == "1") {
syntheticCheckbox.setImageResource(R.drawable.checked);
syntheticCheckbox.setTag("2");
DLCArray[3] = 1;
} else if (syntheticCheckbox.getTag() == "2") {
syntheticCheckbox.setImageResource(R.drawable.checkmark);
syntheticCheckbox.setTag("1");
DLCArray[3] = 0;
}
}
});
ImageButton necroidCheckbox = (ImageButton) findViewById(R.id.necroids_checkbox);
necroidCheckbox.setTag("1");
necroidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (necroidCheckbox.getTag() == "1") {
necroidCheckbox.setImageResource(R.drawable.checked);
necroidCheckbox.setTag("2");
DLCArray[4] = 1;
} else if (necroidCheckbox.getTag() == "2") {
necroidCheckbox.setImageResource(R.drawable.checkmark);
necroidCheckbox.setTag("1");
DLCArray[4] = 0;
}
}
});
ImageButton lithoidCheckbox = (ImageButton) findViewById(R.id.lithoids_checkbox);
lithoidCheckbox.setTag("1");
lithoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (lithoidCheckbox.getTag() == "1") {
lithoidCheckbox.setImageResource(R.drawable.checked);
lithoidCheckbox.setTag("2");
DLCArray[5] = 1;
} else if (lithoidCheckbox.getTag() == "2") {
lithoidCheckbox.setImageResource(R.drawable.checkmark);
lithoidCheckbox.setTag("1");
DLCArray[5] = 0;
}
}
});
ImageButton ancientCheckbox = (ImageButton) findViewById(R.id.ancient_checkbox);
ancientCheckbox.setTag("1");
ancientCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (ancientCheckbox.getTag() == "1") {
ancientCheckbox.setImageResource(R.drawable.checked);
ancientCheckbox.setTag("2");
DLCArray[6] = 1;
} else if (ancientCheckbox.getTag() == "2") {
ancientCheckbox.setImageResource(R.drawable.checkmark);
ancientCheckbox.setTag("1");
DLCArray[6] = 0;
}
}
});
ImageButton federationsCheckbox = (ImageButton) findViewById(R.id.federations_checkbox);
federationsCheckbox.setTag("1");
federationsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (federationsCheckbox.getTag() == "1") {
federationsCheckbox.setImageResource(R.drawable.checked);
federationsCheckbox.setTag("2");
DLCArray[7] = 1;
} else if (federationsCheckbox.getTag() == "2") {
federationsCheckbox.setImageResource(R.drawable.checkmark);
federationsCheckbox.setTag("1");
DLCArray[7] = 0;
}
}
});
ImageButton apocalypseCheckbox = (ImageButton) findViewById(R.id.apocalypse_checkbox);
apocalypseCheckbox.setTag("1");
apocalypseCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (apocalypseCheckbox.getTag() == "1") {
apocalypseCheckbox.setImageResource(R.drawable.checked);
apocalypseCheckbox.setTag("2");
DLCArray[8] = 1;
} else if (apocalypseCheckbox.getTag() == "2") {
apocalypseCheckbox.setImageResource(R.drawable.checkmark);
apocalypseCheckbox.setTag("1");
DLCArray[8] = 0;
}
}
});
ImageButton utopiaCheckbox = (ImageButton) findViewById(R.id.utopia_checkbox);
utopiaCheckbox.setTag("1");
utopiaCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (utopiaCheckbox.getTag() == "1") {
utopiaCheckbox.setImageResource(R.drawable.checked);
utopiaCheckbox.setTag("2");
DLCArray[9] = 1;
} else if (utopiaCheckbox.getTag() == "2") {
utopiaCheckbox.setImageResource(R.drawable.checkmark);
utopiaCheckbox.setTag("1");
DLCArray[9] = 0;
}
}
});
}
public static void writeToFile() throws IOException {
int len = DLCArray.length;
for (int i = 0; i < len; i++) {
FileWriter writer = new FileWriter("hasDLC.txt");
writer.write(DLCArray[i] + "\t"+ "");
}
}
}
second page
package com.example.stellarisspeciesrandomizer;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Randomizer {
private static int[] tall= new int[3] ;
public static String RandomSpecies(String origin) throws FileNotFoundException {
readFile();
Random random = new Random();
ArrayList<String> originArray = new ArrayList<String>();
String origins1 = "Prosperous Unification";
String origins2 = "Galactic Doorstep";
String origins3 = "Lost Colony";
String origins4 = "Here Be Dragons";
String origins5 = "Ocean Paradise";
String origins6 = "Clone Army";
String origins7 = "Necrophage";
String origins18 = "Resource Consolidation";
String origins19 = "Remnants";
String origins16 = "Life Seeded";
String origins17 = "Post-Apocalyptic";
String origins8 = "Remnants";
String origins9 = "Shattered Ring";
String origins10 = "Void Dwellers";
String origins11 = "Scion";
String origins12 = "On The Shoulders of Giants";
String origins13 = "Common Ground";
String origins14 = "Hegemon";
String origins15 = "Doomsday";
String origin20 = "Syncretic Evolution";
String origin21 = "Mechanist";
String origin22 = "String of Life";
originArray.add(origins4);
originArray.add(origins5);
originArray.add(origins6);
originArray.add(origins7);
originArray.add(origins18);
originArray.add(origins19);
originArray.remove(origins17);
originArray.remove(origins16);
originArray.add(origins8);
originArray.add(origins9);
originArray.add(origins10);
originArray.add(origins11);
originArray.add(origins12);
originArray.add(origins13);
originArray.add(origins14);
originArray.add(origins15);
originArray.add(origin20);
originArray.add(origin21);
originArray.add(origin22);
originArray.add(origins1);
originArray.add(origins2);
originArray.add(origins3);
origin = originArray.get(random.nextInt(originArray.size()));
return origin;
}
public static void readFile() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("hasDLC.txt"));
tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
System.out.println(tall);
}
}
last page
package com.example.stellarisspeciesrandomizer;
import static com.example.stellarisspeciesrandomizer.Randomizer.RandomSpecies;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileNotFoundException;
public class RandomizerHome extends AppCompatActivity {
String hi = "hi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.randomizer_layout);
ImageView originImageView =(ImageView) findViewById(R.id.originImageView);
Intent dlcIntent = new Intent(this, DLCPage.class);
Button dlcButton = (Button) findViewById(R.id.dlc_button);
dlcButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dlcIntent);
}
});
Button randomizeButton = (Button) findViewById(R.id.randomize_button);
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
String originTrue = "hi";
originTrue = RandomSpecies(hi);
switch(originTrue){
case ("Prosperous Unification"): originImageView.setImageResource(R.drawable.prosperousunification);break;
case ("Galactic Doorstep"): originImageView.setImageResource(R.drawable.galacticdoorstep);break;
case ("Lost Colony"): originImageView.setImageResource(R.drawable.lostcolony);break;
case ("Here Be Dragons"): originImageView.setImageResource(R.drawable.here_be_dragons);break;
case ("Ocean Paradise"): originImageView.setImageResource(R.drawable.ocean_paradise);break;
case ("Clone Army"): originImageView.setImageResource(R.drawable.clones);break;
case ("Necrophage"): originImageView.setImageResource(R.drawable.necrophage);break;
case ("Resource Consolidation"): originImageView.setImageResource(R.drawable.resource_consolidation);break;
case ("Remnants"): originImageView.setImageResource(R.drawable.remnant);break;
case ("Life Seeded"): originImageView.setImageResource(R.drawable.life_seeded);break;
case ("Post-Apocalyptic"): originImageView.setImageResource(R.drawable.post_apocalyptic);break;
case ("Shattered Ring"): originImageView.setImageResource(R.drawable.shattered_ring);break;
case ("Void Dwellers"): originImageView.setImageResource(R.drawable.void_dwellers);break;
case ("Scion"): originImageView.setImageResource(R.drawable.scion);break;
case ("On The Shoulders of Giants"): originImageView.setImageResource(R.drawable.on_the_shoulders_of_giant);break;
case ("Common Ground"): originImageView.setImageResource(R.drawable.common_ground);break;
case ("Hegemon"): originImageView.setImageResource(R.drawable.hegemon);break;
case ("Doomsday"): originImageView.setImageResource(R.drawable.doomsday);break;
case ("Syncretic Evolution"): originImageView.setImageResource(R.drawable.syncretic_evolution);break;
case ("Mechanist"): originImageView.setImageResource(R.drawable.mechanist);break;
case ("Tree of Life"): originImageView.setImageResource(R.drawable.tree_of_life);break;
}
System.out.println(originTrue);
}
});
}
}
Here:
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
What you are doing here: define an anonymous subclass of View.OnClickListener. And when you check the documentation for that class, it says:
public abstract void onClick (View v)
Now read the compiler message again you got. overridden method does not throw 'java.io.FileNotFoundException'
Thus the real answer here is: A) you have to understand what you are doing and B) you have to read compiler error messages really carefully.
Long story short, you can not override an inherited method and add checked exceptions such as FileNotFoundException to the signature of your method. So, the solution is to step back and to really learn/understand how exception handling works in Java. One possibility here: use try/catch in your readFile(), catch the FileNotFoundException and rethrow it as (unchecked) RuntimeException. Then you do not need to have throws FileNotFoundException on your method signatures, and the compiler won't complain any more.
Hello all, I would like my number (resultat) seems like this ###,###,###.00. Into (resultat) in the String.valueOf from the below phrase of the below Java Code. Thanks for your answers.
result.setText("the rent is " + String.valueOf(resultat) + " currency");
package albencreation.realestateapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Rent extends AppCompatActivity {
EditText price = null;
EditText profit = null;
TextView result = null;
Button envoyer = null;
Button close = null;
Button info = null;
Button clear = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rent);
price = (EditText) findViewById(R.id.price);
profit = (EditText) findViewById(R.id.profit);
result = (TextView) findViewById(R.id.result);
envoyer = (Button) findViewById(R.id.buttcalculate);
close = (Button) findViewById(R.id.buttclose);
info = (Button) findViewById(R.id.buttinfo);
clear = (Button) findViewById(R.id.buttclear);
envoyer.setOnClickListener(envoyerListener);
close.setOnClickListener(closeListener);
info.setOnClickListener(infoListener);
clear.setOnClickListener(clearListener);
}
private OnClickListener envoyerListener = new OnClickListener() {
#Override
public void onClick(View v) {
String p = price.getText().toString();
String o = profit.getText().toString();
float pValue;
if (p.isEmpty()) {
pValue = 0;
} else {
pValue = Float.valueOf(p);
}
float oValue;
if (o.isEmpty()) {
oValue = 0;
} else {
oValue = Float.valueOf(o);
}
float resultat = oValue * pValue / 100;
result.setText("the rent is " + String.valueOf(resultat) + " currency");
}
};
private OnClickListener closeListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, MainActivity.class);
startActivity(jumpage);
}
};
private OnClickListener infoListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, Inforent.class);
startActivity(jumpage);
}
};
private OnClickListener clearListener = new OnClickListener() {
#Override
public void onClick(View v) {
price.getText().clear();
profit.getText().clear();
String defaut = "result rent";
result.setText(defaut);
}
};
}
Use DecimalFormat to format the string as you like. For integer values use # and for decimal places use 0
DecimalFormat formatter = new DecimalFormat("###,###,###.00");
String resultString = formatter.format(resultat);
result.setText("the rent is " + resultString + " currency");
try this :
import java.text.DecimalFormat;
float f = YourValue;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f));
This code for show Two Dights Hope will help you
Hi I am New to java and trying to develop an already existing Anti-ragging application to support newer api like lollipop from gingerbread. I have decompiled the apk and extracted the source code and built it in Gradle system.
Although the source code is correct,I am getting 3 errors in java code...not been able to figure out from a week.
The app contains 4 screens. The main screen is with a send button to send message, the second settings screen with two buttons to set message which we want to send and set contacts whom we want to send the message... the other two screens are the custom dialog layouts of the Set Meaasge & contact.
No errors in this main Java file just giving it for a reference
MainActivity.java:
package com.eminem.sharath.antiragging;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String[] arrr1;
private ImageButton ib1;
private double latitude;
private LocationManager lm;
private double longitude;
private SharedPreferences sp;
private SharedPreferences sp1;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setLogo(R.mipmap.ic_launcher);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
this.ib1 = (ImageButton)findViewById(R.id.imageButton1);
this.lm = (LocationManager)getSystemService(LOCATION_SERVICE);
this.ib1.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
MainActivity.this.sp = MainActivity.this.getSharedPreferences("demo", 1);
final String str1 = MainActivity.this.sp.getString("aaa", "");
MainActivity.this.sp1 = MainActivity.this.getSharedPreferences("sdat", 1);
String str2 = MainActivity.this.sp1.getString("snum", "");
MainActivity.this.arrr1 = str2.split(",");
Toast.makeText(MainActivity.this.getApplicationContext(), str2 + str1, Toast.LENGTH_SHORT).show();
System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + str2 + str1);
MainActivity.this.lm.requestLocationUpdates("gps", 1000L, 5.0F, new LocationListener() {
public void onLocationChanged(Location paramAnonymous2Location) {
Location localLocation = MainActivity.this.lm.getLastKnownLocation("gps");
MainActivity.this.latitude = localLocation.getLatitude();
MainActivity.this.longitude = localLocation.getLongitude();
Toast.makeText(MainActivity.this.getApplicationContext(), "Latitude:" + MainActivity.this.latitude + "\n" + "Longitude:" + MainActivity.this.longitude, Toast.LENGTH_SHORT).show();
String str = "http://maps.google.com/maps?=" + MainActivity.this.latitude + "," + MainActivity.this.longitude;
for (int i = 0; ; i++) {
if (i >= MainActivity.this.arrr1.length) {
return;
}
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + MainActivity.this.arrr1);
SmsManager.getDefault().sendTextMessage(MainActivity.this.arrr1[i], null, str1 + " Come at this location" + str, null, null);
}
}
public void onProviderDisabled(String paramAnonymous2String) {
}
public void onProviderEnabled(String paramAnonymous2String) {
}
public void onStatusChanged(String paramAnonymous2String, int paramAnonymous2Int, Bundle paramAnonymous2Bundle) {
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
startActivity(new Intent(getApplicationContext(), Settingss.class));
return super.onOptionsItemSelected(item);
}
}
The three errors are in this settings file...i have commented the error name beside the error for reference.
Settings.java:
package com.eminem.sharath.antiragging;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MultiAutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView.CommaTokenizer;
import android.widget.Toast;
import java.io.PrintStream;
import java.util.ArrayList;
public class Settingss extends AppCompatActivity
{
private ArrayList<String> alist = new ArrayList();
private Button b1;
private Button b2;
SharedPreferences.Editor ed;
private String setnum = "";
SharedPreferences sp;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.contact);
this.b1 = ((Button)findViewById(R.id.button1));
this.b2 = ((Button)findViewById(R.id.button2));
this.b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
Settingss.this.showDialog(1);
}
});
this.b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
Settingss.this.showDialog(2);
}
});
}
protected Dialog onCreateDialog(int paramInt) {
if (paramInt == 1) {
final Dialog localDialog1 = new Dialog(this);
localDialog1.setContentView(R.layout.tosetmessage);
localDialog1.setTitle("Set Message");
final EditText localEditText = (EditText)findViewById(R.id.editText1);
Button localButton1 = (Button)findViewById(R.id.button1);
Button localbutton2 = ((Button) findViewById(R.id.button2));
localbutton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
Settingss.this.sp = Settingss.this.getSharedPreferences("demo", 2);
Settingss.this.ed = Settingss.this.sp.edit();
Settingss.this.ed.putString("aaa", localEditText.getText().toString());
Settingss.this.ed.commit();
localDialog1.dismiss();
}
});
localButton1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
localDialog1.dismiss();
}
});
localDialog1.show();
}
while(true)
{
return super.onCreateDialog(paramInt);
/*Error: unreachale statement*/ if (paramInt == 2)
{
final Dialog localDialog2 = new Dialog(this);
localDialog2.setContentView(R.layout.multiautotext);
localDialog2.setTitle("Set Contacts");
final MultiAutoCompleteTextView localMultiAutoCompleteTextView = (MultiAutoCompleteTextView)localDialog2.findViewById(R.id.multiAutoCompleteTextView1);
Button localButton2 = (Button)localDialog2.findViewById(R.id.button1);
Button localButton3 = (Button)localDialog2.findViewById(R.id.button2);
Cursor localCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, "display_name ASC");
if (localCursor.moveToFirst())
{
do
{
String str1 = localCursor.getString(localCursor.getColumnIndex("display_name"));
String str2 = localCursor.getString(localCursor.getColumnIndex("data1"));
String str3 = str1 + "%" + str2;
this.alist.add(str3);
} while (localCursor.moveToNext());
ArrayAdapter localArrayAdapter = new ArrayAdapter(this, R.layout.simple_list_item, this.alist);
localMultiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
localMultiAutoCompleteTextView.setAdapter(localArrayAdapter);
}
localButton2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
String[] arrayOfString = localMultiAutoCompleteTextView.getText().toString().split(",");
int i = 0;
if (i >= arrayOfString.length)
{
System.out.println("************************" + Settingss.this.setnum);
Toast.makeText(Settingss.this.getApplicationContext(), Settingss.this.setnum, Toast.LENGTH_SHORT).show();
Settingss.this.sp = Settingss.this.getSharedPreferences("sdat", 2);
Settingss.this.ed = Settingss.this.sp.edit();
Settingss.this.ed.putString("snum", Settingss.this.setnum);
Settingss.this.ed.commit();
Settingss.this.setnum = "";
Settingss.this.finish();
return;
}
String str2;
if (arrayOfString[i].contains("%"))
str2 = arrayOfString[i].split("%")[1];
String str1;
for (Settingss.this.setnum = (Settingss.this.setnum + /*Error: Variable Str2 might not have been initialized*/ str2 + ",");; Settingss.this.setnum = (Settingss.this.setnum + str1 + ","))
{
i++;
break;
/*Error: unreachale statement*/ str1 = arrayOfString[i];
}
}
});
localButton3.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
localDialog2.dismiss();
}
});
localDialog2.show();
}
}
}
}
Please help me debug the application.
I have no intention to take any credits for the application because as I haven't developed it...just want to play with the user interface and give it a taste of new api.
The return statement will cause the onCreateDialog method to return and any subsequent lines will not be executed. That's why you get the unreachable code error message. Similarly, the break statement will cause the for loop to end. Any subsequent lines will not be executed.
Finally, you get a /*Error: Variable Str2 might not have been initialized*/ error because all local variables must be initialized before they can be used for the first time.
For /*Error: Variable Str2 might not have been initialized*/:
Change String str2; to String str2 = "";
As for the other two errors, you have a return; and break; before those lines.
Any statements after a unconditional return and break will be unreachable, i.e. there is no way that the code there (subsequent lines) will execute.
In my program, I have only 1 button. And first press the program will output a random string. If the user presses it again to stop, my program will slow random (delay) the same slot machine. How can I do it?
my code
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Randomsentence extends Activity {
boolean showRandom = false;
TextView txt;
int time = 30;
int random;
public String[] myString;
Button bt1;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
Medaiplayer mp = new Medaiplayer();
Mediaplayer mp2 = new Mediaplayer();
mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1);
mp2 = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile2);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showRandom = !showRandom;
t = new Thread() {
public void run() {
try {
while (showRandom) {
mp.start();
mp2.reset();
mp2.prepare();
sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
mp.reset();
mp.prepare();
mp2.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
});
}
// our handler
Handler handler = new Handler() {
public void handleMessage(Message msg) {//display each item in a single line
{
Random rgenerator = new Random();
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
txt.setText(q);
}
}
};
}
Ignoring the MediaPlayer part, I think it should be this way:
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Randomsentence.R;
public class Randomsentence extends Activity {
TextView txt;
int random;
public String[] myStrings;
Button bt1;
private static final int MESSAGE_RANDOM = 1;
private static final long MIN_INTERVAL = 500;
private static final long MAX_INTERVAL = 1500;
private static final long STEP = 60;
private long mInterval = 0;
private boolean mStarted = false;
private Random mRandom = new Random();
private Handler mHandler = new Handler() {
#Override
public void handleMessage (Message msg) {
if(msg.what == MESSAGE_RANDOM) {
showRandomString();
if(mStarted) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
} else {
if(mInterval <= MAX_INTERVAL) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
mInterval += STEP;
} else {
this.removeMessages(MESSAGE_RANDOM);
Toast.makeText(Randomsentence.this, "Stopped!", Toast.LENGTH_SHORT).show();
}
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(mBt1OnClick);
myStrings = getResources().getStringArray(R.array.myArray);
}
private void showRandomString() {
final int index = mRandom.nextInt(myStrings.length - 1);
txt.setText(myStrings[index]);
}
private OnClickListener mBt1OnClick = new OnClickListener() {
#Override
public void onClick(View v) {
if(!mStarted) {
// Start
Toast.makeText(Randomsentence.this, "Started!", Toast.LENGTH_SHORT).show();
mStarted = true;
mInterval = MIN_INTERVAL;
mHandler.removeMessages(MESSAGE_RANDOM);
mHandler.sendEmptyMessage(MESSAGE_RANDOM);
} else {
// Stop
mStarted = false;
Toast.makeText(Randomsentence.this, "Stoping...", Toast.LENGTH_SHORT).show();
}
}
};
}
When press button first sound active. Then press that button again it will stop and second sound active My code is OK?
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Randomsentence extends Activity {
boolean showRandom = false;
TextView txt;
int time = 30;
int random;
public String[] myString;
Button bt1;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt=(TextView)findViewById(R.id.txt);
bt1 = (Button)findViewById(R.id.bt1);
Medaiplayer mp = new Medaiplayer();
Mediaplayer mp2 = new Mediaplayer();
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showRandom = !showRandom;
t = new Thread() {
public void run() {
try {
while(showRandom){
mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1);
mp.setLooping(true);
mp.start();
mp2.reset();
mp2.prepare();
sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
mp.reset();
mp.prepare();
mp2 = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile2);
mp2.setLooping(true);
mp2.start();
}catch(Exception ex){
ex.printStackTrace();
}
}
};
t.start();
}
});
}
// our handler
Handler handler = new Handler() {
public void handleMessage(Message msg) {//display each item in a single line
{
Random rgenerator = new Random();
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
txt.setText(q);
}
}
};
}
Add the line:
mp.setLooping(true);
Then set false when you want to stop it looping.
Your code has several errors. Typos, cases,
ex.: Medaiplayer should be MediaPlayer
This alone would be enough to cause the error. Also, declaring your variables outside the method is a good idea.