我正在尝试使用gridview创建一个单词搜索,但我不确定如何从JSONArray添加行,但我的应用程序此时仍然崩溃,并且gridView.addView(tableRow);
这是我的新拼图课程
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();
}
}
错误日志
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)
答案 0 :(得分:0)
问题是你不能addView(view)
直接GridView,因为它是AdapterView
,不允许这样做。因此,您必须在Adapter
中执行此操作。您只需向适配器添加更多数据,然后在适配器上调用notifyDataSetChanged()
后,您的GridView
将自行添加View
。