Creating a Gridview for a word search - android

I am trying to create a word search using a gridview but I'm unsure how to add rows from a JSONArray, but my app keeps crashing at this point and also at gridView.addView(tableRow);
This is my new puzzle class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Arrays;
public class NewPuzzleActivity extends Activity implements OnRetrieveHTTPData {
//word search data
String[] rows;
String[] words;
char[] letters;
//variables for the grid creation
int letterID = 0;
int rowID = 0;
//found words by the user
String[] wordsFound;
int[] rowFound;
int[] columnFound;
int[]directionFound;
// objects within the game *miscellaneous properties*
boolean firstLetterSelected = false;
int numOFLettersSelected = 0;
int[] lettersSelected;
int[] rowsSelected;
int[] columnsSelected;
String selectedString = "";
int directionSelected = 0;
int lastLetterSelected = -1;
String date;
GridView gridView;
TextView textView;
Toast toast;
public NewPuzzleActivity(){
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_puzzle);
gridView = (GridView) findViewById(R.id.gridView1);
Intent intent = getIntent();
if(intent.hasExtra("rows")){
// initialize the data
rows = intent.getExtras().getStringArray("rows");
addRows();
stringArrayToCharArray();
fillGrid();
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
if(intent.hasExtra("words")){
words = intent.getExtras().getStringArray("words");
wordsFound = new String[words.length];
rowFound = new int[words.length];
columnFound = new int[words.length];
directionFound = new int[words.length];
fillWords();
}
if(intent.hasExtra("date")){
date = intent.getExtras().getString("date");
//textView = (TextView)findViewById(R.id.Title);
//textView.append(date);
}
}
public void letterButonClick(View view){
if(toast != null){
toast.cancel(); // cancel toast message to prevent multiple toast messages
}
TextView textView1 = (TextView) findViewById(view.getId());
textView1.setTextColor(Color.RED);
//works out the column number of the selected letter(s)
columnsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[numOFLettersSelected] == 0) columnsSelected[numOFLettersSelected] = rows.length;
//works out the row number of the selected letter(s)
rowsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())/ rows.length)+1;
if(rowsSelected[numOFLettersSelected] == 0) rowsSelected[numOFLettersSelected] = rows.length;
//fixes the last column
if(columnsSelected[numOFLettersSelected] == rows.length) rowsSelected[numOFLettersSelected]-=1;
lettersSelected[numOFLettersSelected] = Integer.parseInt(view.getTag().toString()) + 4999;
Log.i("Selected Column", Integer.toString(columnsSelected[numOFLettersSelected]));
Log.i("Selected Row", Integer.toString(rowsSelected[numOFLettersSelected]));
if(!firstLetterSelected){
firstLetterSelected = true;
//resets the selected string
selectedString = textView1.getText().toString();
numOFLettersSelected = 1;
}else{
//adds letters to selected string
selectedString += textView1.getText().toString();
//compares to the last letter to work out the direction
if(columnsSelected[numOFLettersSelected] +1 == columnsSelected[numOFLettersSelected - 1] &&
rowsSelected[numOFLettersSelected] +1 == rowsSelected[numOFLettersSelected - 1]){
//direction left / down
directionSelected = 0;
Log.i("Direction", "0");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is down
directionSelected = 1;
Log.i("Direction", "1");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected] - 1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]){
//direction is right-down
directionSelected = 2;
Log.i("Direction", "2");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is left
directionSelected = 3;
Log.i("Direction", "3");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is right
directionSelected = 4;
Log.i("Direction", "4");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]){
//direction is left-up
directionSelected = 5;
Log.i("Direction", "5");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is up
directionSelected = 6;
Log.i("Direction", "6");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]) {
//direction is right-up
directionSelected = 7;
Log.i("Direction", "7");
checkWordFound();
}else{
// not a letter within/ around the the first letter selected, reset any selected letters
//deselect words and select a new letter to starr again
//selected string reset
selectedString = textView1.getText().toString();
for(int i : lettersSelected){
try{
TextView letters = (TextView)findViewById(i);
letters.setTextColor(Color.BLACK);
i++;
}catch (Exception e){
//break
Toast.makeText(getApplication(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
// new letter to be selected
columnsSelected[0] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[0] == 0) columnsSelected[0] = rows.length;
rowsSelected[0] = (Integer.parseInt(view.getTag().toString()) / rows.length)+1;
if(rowsSelected[0] == 0) rowsSelected[0] = rows.length;
if(columnsSelected[0] == rows.length) rowsSelected[0] -= 1;
lettersSelected[0] = Integer.parseInt(view.getTag().toString()) + 4999;
textView1.setTextColor(Color.RED);
}
numOFLettersSelected++;
Log.i("Selected TEXT", selectedString);
}
lastLetterSelected = Integer.parseInt(view.getTag().toString());
}
private void fillGrid(){
int LetterChars = 0;
for(int i = 0; i < rows.length * rows.length; i++){
if(LetterChars >= rows.length){
rowID--;
LetterChars = 0;
}
addLetter((TableRow)findViewById(rowID+4000+ rows.length-1));
TextView textView1 = (TextView)findViewById(i+5000);
textView1.setText(Character.toString(letters[i]));
LetterChars++;
}
}
private void fillWords(){
for(int i = 1; i < rows.length -1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
textView1.setText(words[i-1]);
}catch(Exception e){
textView1.setText("");
}
}
}
}
private void stringArrayToCharArray(){
char[] chars = new char[rows.length * rows.length];
int i = 0;
//selection of strings
for(int j = 0; j< rows.length; j++){
// selection of letters
for(int k = 0; k < rows.length; k++){
try{
chars[i] = rows[j].charAt(k);
}catch (Exception e){
Log.e("Error", "Error when adding chars");
}
i++;
}
}
letters = chars;
}
private void addLetter(TableRow row){
TextView textView1 = new TextView(this);
textView1.setId(letterID+5000);
textView1.setPadding(3,3,3,3);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
TableRow.LayoutParams textLayout = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
textLayout.setMargins(10,0,0,10);
textView1.setTextAlignment(textView1.TEXT_ALIGNMENT_CENTER);
textView1.setGravity(Gravity.CENTER);
textView1.setTag(""+(letterID+1));
textView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
letterButonClick(v);
}
});
textView1.setOnDragListener(new View.OnDragListener() {
//draggin selection *To be implemented*
#Override
public boolean onDrag(View v, DragEvent event) {
return false;
}
});
textView1.setLayoutParams(textLayout);
row.addView(textView1);
letterID++;
}
private void addRows(){
for(int i= 0; i < rows.length;i++){
TableRow tableRow = new TableRow(this);
tableRow.setId(i+4000);
gridView.addView(tableRow);
}
}
private void checkWordFound(){
int foundID = 0;
for(String w: words){
if(selectedString.contains(w)){
//word that have been found
Log.i("Word Found", "Found: " + w);
//highlight words that have been found in the word list
for(int i = 1; i < rows.length-1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
if(textView1.getText().equals(w)){
//textview that contains the found words
textView1.setTextColor(Color.GREEN);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
//add to found
wordsFound[foundID] =w;
columnFound[foundID] = columnsSelected[0];
rowFound[foundID] = rowsSelected[0];
directionFound[foundID] = directionSelected;
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
foundID++;
}
checkCompletion();
//no words are found
}
private void checkCompletion(){
if(Arrays.equals(words, wordsFound)){
new AlertDialog.Builder(this)
.setTitle("Word Search Complete")
.setMessage("Submit Score?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//submit score
submitResults();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
}
public void homeClicked(View v){
finish();
}
public void submitResults(){
}
#Override
public void onRetrieveTaskCompleted(String httpData) {
Log.i("Solution Response", responseData);
//debug toasts
Toast.makeText(getApplication(),("Solution Submitted"), Toast.LENGTH_LONG).show();
finish();
}
}
error log
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-04 00:49:18.929 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone D/AndroidRuntime﹕ Shutting down VM
05-04 00:49:18.937 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: sl.lloyd.steve.angrywordsearchthefinalone, PID: 6068
java.lang.RuntimeException: Unable to start activity ComponentInfo{sl.lloyd.steve.angrywordsearchthefinalone/sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.widget.AdapterView.addView(AdapterView.java:461)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.addRows(NewPuzzleActivity.java:320)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.onCreate(NewPuzzleActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

The problem is you cannot addView(view) directly to GridView, because it is an AdapterView which does not allow that. So you have to do this operation in your Adapter. You just have to add more data to the adapter and after call notifyDataSetChanged() on the adapter, so your GridView will be added the View by itself.

Related

Open a actvity when a if statement comes true

Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
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.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);

GridView Pops out NullPointerException

The rows are coming in reverse order. It should be Monday then Tuesday then WednesdayI have a gridview which dynamically fetches data of current week(i.e monday to today). I am facing two issues.
1) My gridView elements are not arranged properly.
2) GridView shows data of that day also whose data does not exists. It simply copies all previous row values. I know rearrangement problem is because of resetPosition variable not getting updated. but if i update it, i get NullPointerException. How can i get rid of these problems?
public class ViewTimeTable extends AppCompatActivity {
private ArrayList<String> mondayStrength,tuesdayStrength,wednesdayStrength,thursdayStrength,fridayStrength;
String [] currentWeek;
int resetPosition;
private Date date;
private Map map;
private int position,pos;
private TextView classTextView,sectionTextView,dateTextView;
private String Class,section,today,day;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one_day_layout);
classTextView = (TextView)findViewById(R.id.class_textView);
sectionTextView = (TextView)findViewById(R.id.section_textView);
dateTextView = (TextView)findViewById(R.id.date_textView);
Intent intent = getIntent();
ParseAnalytics.trackAppOpenedInBackground(intent);
mondayStrength = new ArrayList<String>();
tuesdayStrength = new ArrayList<>();
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ignored) {
}
map = new HashMap();
String[] lectureTimings = {"Lec/Day","I","II","III","IV","V","VI"};
for(int i =0;i<lectureTimings.length;i++){
mondayStrength.add(lectureTimings[i]);
pos = i;
}
System.out.println(position);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Lectures");
GridView mondayRow = (GridView)findViewById(R.id.mon_grid_view);
final GridAdapterChirag mondayAdapter = new GridAdapterChirag(ViewTimeTable.this,R.layout.grid_element, mondayStrength);
mondayRow.setAdapter(mondayAdapter);
System.out.println(position);
currentWeek = getThisWeek();
Class = intent.getStringExtra("Class");
section = intent.getStringExtra("Section");
position = pos+1;
System.out.println(position);
classTextView.append(Class);
sectionTextView.append(section);
resetPosition=position;
String [] day = {"Mon","Tue","Wed","Thu","Fri"};
for(int i=0;i<currentWeek.length;i++) {
mondayStrength.add(position, day[i]);
System.out.print("ResetPosition before loop"+resetPosition);
query.whereEqualTo("Date", currentWeek[i]);
try {
List<ParseObject> objects = query.find();
for (ParseObject object : objects) {
String lid = object.getString("LectureID");
if (lid.substring(7, 9).equals(Class)) {
String m = String.valueOf(lid.charAt(10));
if (m.equals(section)) {
String periodNumber = lid.substring(4, 6);
if (periodNumber.equals("01"))
position += 1;
else if (periodNumber.equals("02"))
position += 2;
else if (periodNumber.equals("03"))
position += 3;
else if (periodNumber.equals("04"))
position += 4;
else if (periodNumber.equals("05"))
position += 5;
else if (periodNumber.equals("06"))
position += 6;
else
position = 100;
map.put(position, object.getString("Strength"));
}
}
System.out.println("ResetPosition"+resetPosition);
System.out.println("Position"+position);
position = resetPosition;
}
System.out.println(map);
for (int k = 1; k <= map.size(); k++) {
mondayStrength.add(resetPosition + k, map.get(resetPosition+k).toString());
}resetPosition+=7;
System.out.println(mondayStrength.size());
//position++;
//mondayAdapter.notifyDataSetChanged();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
//This method simply returns array of dates of current week
private String[] getThisWeek() {
int factor;
ArrayList<String> week = new ArrayList<>();
long oneDay = 86400000;
Calendar calendar = Calendar.getInstance();
long todayInMillis = calendar.getTimeInMillis();
String date;
String todaysDay = new SimpleDateFormat("EEE").format(new Date());
if(todaysDay.equals("Mon"))
factor = 0;
else if(todaysDay.equals("Tue"))
factor = 1;
else if(todaysDay.equals("Wed"))
factor = 2;
else if(todaysDay.equals("Thu"))
factor = 3;
else if(todaysDay.equals("Fri"))
factor = 4;
else if(todaysDay.equals("Sat"))
factor = 5;
else
factor = 6;
for(;factor>=0;factor--){
calendar.setTimeInMillis(todayInMillis-factor*oneDay);
Date d = new Date(calendar.getTimeInMillis());
date = new SimpleDateFormat("dd-MM-yyyy").format(d);
week.add(date);
}
String [] runningWeek = new String[week.size()];
runningWeek = week.toArray(runningWeek);
return runningWeek;
}
LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tonystark.adminlogin/com.example.tonystark.adminlogin.ViewTimeTable}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.tonystark.adminlogin.ViewTimeTable.onCreate(ViewTimeTable.java:126)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358) 
at android.app.ActivityThread.access$600(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:153) 
at android.app.ActivityThread.main(ActivityThread.java:5297) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
at dalvik.system.NativeStart.main(Native Method) 

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=8; index=8

hi dear here I am posting my whole class where I am getting problem. First I explain my problem. I am generating an arrayList "Items" using spinners and the elements in spinners and arrays are exactly same then After comparing array length and ArayList size I want to jump on next activity but problem is occoured in comparing arrays now please help me for this problem
Thanks here is my activity
package com.example.mine4.pantryrecipes;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.util.List;
import java.util.ArrayList;
import android.view.View;
import android.widget.Toast;
import android.widget.Button;
import android.widget.TextView;
public class AddItem extends Activity {
MultiSelectionSpinner spinner1,spinner2,spinner3,spinner4;
Button button1;
TextView tv;
private int count = 0;
List<String> Items=new ArrayList<>();
List<String> veg=new ArrayList<>();
List<String> spice=new ArrayList<>();
List<String> dairy=new ArrayList<>();
ArrayList<Boolean> subset = new ArrayList<>();
String[] arrayRecipe = { "chicken","vegetable oil","ginger",
"onion", "garlic","potatoes","tomatoes","roasted peanuts", "peanut butter"};
String[] arrayRecipe2 = { "chicken","garlic","vegetable oil", "tomatoes",
"Dijon mustard","breadcrumbs","Parmesan cheese","unsalted butter"};
String[] arrayRecipe3 = { "chicken", "vegetable oil","unsalted butter",
"sugar", "garlic", "sauce"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
button1=(Button)findViewById(R.id.button1);
tv=(TextView)findViewById(R.id.tv);
String[] arrayItems = {"chicken"};
String[] arrayVeg = { "vegetable oil", "ginger",
"garlic","potatoes" ,"tomatoes","onion"};
String[] arraySpice = { "roasted peanuts", "sauce","Dijon mustard" };
String[] arrayDairy = { "breadcrumbs", "Parmesan cheese", "unsalted butter","sugar", "peanut butter" };
spinner1 = (MultiSelectionSpinner) findViewById(R.id.mySpinner1);
spinner2 = (MultiSelectionSpinner) findViewById(R.id.mySpinner2);
spinner3 = (MultiSelectionSpinner) findViewById(R.id.mySpinner3);
spinner4= (MultiSelectionSpinner) findViewById(R.id.mySpinner4);
spinner1.setItems(arrayItems);
spinner2.setItems(arrayVeg);
spinner3.setItems(arraySpice);
spinner4.setItems(arrayDairy);
}
public void onClick(View v)
{
Items=spinner1.getSelectedStrings();
veg=spinner2.getSelectedStrings();
spice=spinner3.getSelectedStrings();
dairy=spinner4.getSelectedStrings();
Items.addAll(veg);
Items.addAll(spice);
Items.addAll(dairy);
// for(int i=0;i<Items.size();i++)
// tv.append(Items.get(i));
compareArray();
//count++;
}
public void compareArray()
{
for(int j = 0 ; j < arrayRecipe.length ; j++)
{
for(int i = 0 ; i <Items.size() ; i++)
{
if((arrayRecipe[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe2[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe3[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
}
}
if(subset != null) {
if ((arrayRecipe.length == subset.size())) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, TenIngreRec.class);
startActivity(nextClass);
finish();
Toast.makeText(getApplicationContext(), "arrayRecipe", Toast.LENGTH_LONG).show();
}
if ((arrayRecipe2.length == subset.size())) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, EightIngreRec.class);
startActivity(nextClass);
finish();
Toast.makeText(getApplicationContext(), "arrayRecipe2", Toast.LENGTH_LONG).show();
}
if ((arrayRecipe3.length == subset.size())) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, EightIngreRec.class);
startActivity(nextClass);
finish();
Toast.makeText(getApplicationContext(), "arrayRecipe3", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Un-Matched", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
Intent intn = new Intent(AddItem.this,Exmain.class);
startActivity(intn);
}
}
and the major problem occured in this code which is array indexOutOfBound
for(int j = 0 ; j < arrayRecipe.length ; j++)
{
for(int i = 0 ; i <Items.size() ; i++)
{
if((arrayRecipe[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe2[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe3[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
}
}
thanks again for helping me
array.Length() always count from 1 not form zero use
arrayRecipe.length -1 in your for loop
Use This
for(int j = 0 ; j < (arrayRecipe.length)-1 ; j++)
{
for(int i = 0 ; i <Items.size() ; i++)
{
if((arrayRecipe[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe2[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe3[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
}
}
Two problems:
You're using the size of arrayRecipe to bound the index of arrayRecipe, arrayRecipe2 and arrayRecipe3 All three arrays are different in size, hence leading to your error. You need 3 different for loops, one for each arrayRecipe.
Your i and j are in the wrong places.
Items.get(j) should be Items.get(i) as you are using Items.size to limit the size of i. Likewise, arrayRecipe.get(i) should be arrayRecipe.get(j).
Also, it is true that getLength() and getSize() start counting from 1 rather than 0 so the index of the final slot is (getLenght() - 1), but by using < as the clause in your for loop handles that.

validation for empty edit text field is not working

I have two TextView, two EditText and two Buttons. I want to set a DialogBox or Toast when the button is clicked without entering any values in the textview. I have two stings, s and s1. If s and s1 or either s or s1 is not entered in the edittext, I must get a toast. I wrote a code for toast but it's not working fine!
Can you help me with this?
This is my code:
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
AnimationDrawable frameanimation;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender=(Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview=(ImageView)findViewById(R.id.imageanim);
imgview.setBackgroundResource(R.drawable.myanim);
frameanimation=(AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
//code for toast//
//if s nd s1 is empty then execute this else executee the rest//
if((s==" ") && (s1==" "))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
else
{
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0,
n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
Change your validation to this :
if((s.equals("")) && (s1.equals("")))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}
Or you can check like this:
if((s.length() == 0) && (s1.length() == 0))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
Tried your code and validation is working :
import java.io.DataInputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
// getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN
// ,WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender = (Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview = (ImageView) findViewById(R.id.imageanim);
frameanimation = (AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
// code for toast//
// if s nd s1 is empty then execute this else executee the rest//
if ((s.equals("")) || (s1.equals(""))) {
Toast.makeText(getBaseContext(), "cnt b empty",
Toast.LENGTH_SHORT).show();
} else {
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0, n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
}
}
}
Try if (s.isEmpty() || s1.isEmpty()) to check if your strings are empty. == and .equals will not work with string comparison because they are comparing the objects and not solely the contents. To check if two strings are equal, you can use firstString.compareTo(anotherString) == 0.
Trim your edittext value then compare
if((("").equals(s.trim())) && (("").equals(s1.trim())))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}

Android MediaPlayer Prepare Failed

I've been trying to make a Javanese language translation along with the sound. the translation result is displayed successfully, but the sound won't come out. it throws exception.
Java.io.IOException: Prepare failed: status=0x1
at android.media.MediaPlayer.prepare(Native Method)
at com.cinta.jawa.JawaSearchActivity.playAudio(JawaSearchActivity.java:51)
at com.cinta.jawa.JawaSearchActivity$1.onClick(JawaSearchActivity.java:178)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8816)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
it says that i got wrong at line 52 and 179, but i have no idea what makes it wrong. Can anybody help me?
here is the code:
package com.cinta.jawa;
import java.io.IOException;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
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 JawaSearchActivity extends Activity {
private EditText etSearch;
private TextView tvResult;
Jawa jawa = new Jawa(this);
boolean booSearch = false;
public static MediaPlayer myplayer = new MediaPlayer();
public static ArrayList<Uri> pathlist = new ArrayList<Uri>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
etSearch = (EditText) findViewById(R.id.editTextSearch);
tvResult = (TextView) findViewById(R.id.textViewResult);
Button btnSearch = (Button) findViewById(R.id.button_search);
btnSearch.setOnClickListener(onClickListener);
}
public void playAudio() {
try {
if (myplayer.isPlaying()) {
myplayer.stop();
myplayer.release();
}
if (pathlist.size() >= 1) {
for (int i = 0; i< pathlist.size();i++){
Uri path = pathlist.get(i);
myplayer.setDataSource(this, path);
myplayer.prepare(); /*this is the error line*/
myplayer.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
myplayer.setLooping(true);
}
private String[] getWord(XmlResourceParser words, String strWord)
throws XmlPullParserException, IOException {
int eventType = -1;
String[] strReturn = new String[2];
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strName = words.getName();
if (strName.equals("word")) {
String wordValue = words.getAttributeValue(null, "key");
if (wordValue.equalsIgnoreCase(strWord)) {
strReturn[0] = words.getAttributeValue(null, "file");
strReturn[1] = words.getAttributeValue(null,
"translate");
return strReturn;
}
}
}
eventType = words.next();
}
return strReturn;
}
OnClickListener onClickListener = new OnClickListener() {
public void onClick(View v) {
XmlResourceParser jawaDictionary = getResources()
.getXml(R.xml.jawa);
String strWord[] = new String[2];
String[] strNumb = null;
int intstrNumb = 0;
String angkaBo = null;
System.out.println("AWAL NIHH??" + angkaBo);
Long angka = null;
boolean booFind = false;
StringBuilder strbTranslate = new StringBuilder();
myplayer.reset();
myplayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
for (int i = 0; i< pathlist.size();i++){
pathlist.remove(i);
if (pathlist.size() >= 1) {
myplayer.reset();
playAudio();
}
}
}
});
String strWords = etSearch.getText().toString().trim();
String[] astrWord = strWords.split(" ");
int intCountWords = astrWord.length;
for (int i = 0; i < intCountWords; i++) {
try {
String perWord = astrWord[i].trim();
int perWordL = perWord.length();
for (int x = 0; x < perWordL; x++) {
if (Character.isDigit(perWord.charAt(x))) {
angka = Long.parseLong(perWord);
}
}
strWord = getWord(jawaDictionary, astrWord[i].trim());
System.out.println("STRWORD NYE APAAN??" + strWord[0]);
jawaDictionary.close();
jawaDictionary = getResources().getXml(R.xml.jawa);
if (strWord[0] != null) {
System.out.println("MASUK SINI GA SIHHHHHH??");
strbTranslate.append(strWord[1]);
strbTranslate.append(" ");
System.out.println("COBA DILIAT " + strbTranslate);
System.out.println("KALOYANG INI?? " + pathlist);
tvResult.setText(strbTranslate);
booSearch = true;
} else {
System.out.println("MASUK MANA DONK??");
if (angka != null) {
angkaBo = NumberScanActivity.convert(angka);
System.out.println("COBA LIAT INI MUNCUL GAKK??"
+ angkaBo);
String angkaNih = angkaBo.trim();
strNumb = angkaNih.split(" ");
System.out.println("HOHOHEHEHEHK??" + angkaNih);
System.out.println("BLUKUTUKKK??" + strNumb);
intstrNumb = strNumb.length;
for (int y = 0; y < intstrNumb; y++) {
System.out
.println("MASUK SINI KAGA?? HAYOOOOOO "
+ strNumb[y]);
strbTranslate.append(strNumb[y]);
strbTranslate.append(" ");
}
tvResult.setText(strbTranslate);
booSearch = true;
}
}
} catch (Exception e) {
}
}
String fullText = strbTranslate.toString();
pathlist = SyllableScanActivity.convertSentenceToSyl(fullText);
System.out.println("COBA LIAT ISI PATHLIS APAAN>>>>>> "+pathlist);
if (!myplayer.isPlaying()) {
playAudio(); /*this is the error line*/
}
if (booFind == false) {
if (booSearch == false)
tvResult.setText("Sorry, No Result");
}
}
};
}
See this link this will help you to solve your problem.
I am using this code in my project for playing audio files. I am not using mediaPlayer.prepair();
see if this help's you...
bGSound = MediaPlayer.create(MusicPlay.this,R.drawable.music_ground);
float bGLeftVol = (float) (bGSoundVolume.getProgress()/100.0);
float bGRightVol = (float) (bGSoundVolume.getProgress()/100.0);
bGSound.setLooping(true);
bGSound.setVolume(bGLeftVol, bGRightVol);
bGSound.start();

Categories

Resources