2

空の結果セットを持つデータベースから値をフェッチするときにjson例外に直面する

以下は私のコードです。問題はありません。唯一の問題は、データベースからのフェッチ値が空のときにjson例外に直面していることです。これをどのように処理しますか? それをどのように処理するのですか?

public class fifthscreen extends Activity {
String num = null;
String _response;
// TextView ingredient;
private RatingBar ratingBar;
// TextView ingredient;
long Menu_ID;
String dish_ID;
View row4;
int IOConnect = 0;
View row3;
final private static int DIALOG_LOGIN = 1;
String status;
private static Handler handler;

ExpandableHeightGridView listview;

CategoryListAdapter3 cla;
String DescriptionAPI;

public Dialog dialog2;
public static int feedbacktype;
public static int myInt;

TextView txt1, txt2, txt3;
TextView ingredient;
ImageView img1;

String SelectMenuAPI;
DataBase db;
String FeedbackAPI;
String FeedbackAPI2;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();


ArrayList<Ingredient> ingredientList = new ArrayList<Ingredient>();

public static String allergen2;
private AQuery androidAQuery;
String name;
public static String FeedbackDishId;
String description;
String mainimage;
String allergen;
String url1;
View viewLoad;
String nutrition;
 String ingredientName;
  String ingredientSub;
  String formattedAsString;
Button FeedbackYummiSlice, FeedbackThisdish, nothanks;
final Context context = this;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fifthscreen);
    img1 = (ImageView) findViewById(R.id.test_button_image);

    txt1 = (TextView) findViewById(R.id.menuname);
    txt3 = (TextView) findViewById(R.id.description);
    ImageView b = (ImageView) findViewById(R.id.button1);
    ingredient = (TextView) findViewById(R.id.ingredient);

    Intent iGet = getIntent();
    ImageView options = (ImageView) findViewById(R.id.options5);
    androidAQuery = new AQuery(this);

    db = new DataBase(getBaseContext());
    try {
        db.createDataBase();
    } catch (IOException e1) {

        e1.printStackTrace();
    }

    options.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent iMenuList = new Intent(fifthscreen.this,
                    LinkButtons.class);
            startActivity(iMenuList);
        }
    });

    dish_ID = iGet.getStringExtra("dish_ID");

    listview = (ExpandableHeightGridView) findViewById(R.id.listview2);
    listview.setExpanded(true);

    cla = new CategoryListAdapter3(fifthscreen.this);
    new TheTask().execute();
    ImageView btnback = (ImageView) findViewById(R.id.btnback);

    btnback.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog2 = new Dialog(context);
            View vLoad = LayoutInflater.from(fifthscreen.this).inflate(
                    R.layout.timer, null);

            dialog2.setContentView(vLoad);

            FeedbackYummiSlice = (Button) dialog2
                    .findViewById(R.id.FeedbackYummiSlice);
            FeedbackThisdish = (Button) dialog2
                    .findViewById(R.id.FeedbackThisdish);
            nothanks = (Button) dialog2.findViewById(R.id.nothanks);




            dialog2.setTitle("FeedBack");

            TextView text = (TextView) dialog2.findViewById(R.id.text);
            text.setText(" I");

            dialog2.setCancelable(false);

            FeedbackYummiSlice.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {

                    showDialog(DIALOG_LOGIN);
                    feedbacktype = 1;
                    FeedbackDishId = "0";

                }
            });

            FeedbackThisdish.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    //
                    showDialog(DIALOG_LOGIN);
                    feedbacktype = 2;
                    FeedbackDishId = dish_ID;

                }
            });

            nothanks.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    //
                    dialog2.dismiss();
                }
            });

            dialog2.show();
        }
    });

 }



public class TheTask extends AsyncTask<Void, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected String doInBackground(Void... arg0) {

        return _response;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

            displayData();


        txt1.setText(name);
        txt3.setText(description);
        androidAQuery.id(img1).image(mainimage, true, true);



        listview.setAdapter(cla);
        cla.notifyDataSetChanged() ;




    }
}

@Override
protected Dialog onCreateDialog(int id) {

    AlertDialog dialogDetails = null;

    switch (id) {
    case DIALOG_LOGIN:
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogview = inflater.inflate(R.layout.dialog_layout, null);

        AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
        dialogbuilder.setTitle("Feedback Form");

        dialogbuilder.setView(dialogview);
        dialogDetails = dialogbuilder.create();

        break;
    }

    return dialogDetails;
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {

    switch (id) {
    case DIALOG_LOGIN:
        final AlertDialog alertDialog = (AlertDialog) dialog;
        Button Submit = (Button) alertDialog.findViewById(R.id.Submitbtn);
        Button cancelbutton = (Button) alertDialog
                .findViewById(R.id.btn_cancel);
        final EditText Email = (EditText) alertDialog
                .findViewById(R.id.Email);
        final EditText Comments = (EditText) alertDialog
                .findViewById(R.id.Comments);

        ratingBar = (RatingBar) alertDialog.findViewById(R.id.ratingBar);





    }
}









private void displayData()  {

    name ="";
    description ="";
    nutrition ="";
    allergen ="";
    mainimage ="";
    ingredientName ="";
    ingredientSub ="";
    formattedAsString="";

    Cursor mCursor = db
            .selectQuery("SELECT * ");

    if (mCursor.moveToFirst()) {
        do {

            name = (mCursor.getString(mCursor.getColumnIndex("name")));
            description 
         =(mCursor.getString(mCursor.getColumnIndex("description")));
            nutrition=(mCursor.getString(mCursor.getColumnIndex("nutrition")));
            allergen=(mCursor.getString(mCursor.getColumnIndex("allergen")));
            mainimage=(mCursor.getString(mCursor.getColumnIndex("image")));
        } while (mCursor.moveToNext());
    }

    mCursor.close();






    Cursor mCursor2 =  db.selectQuery("SELECT ");


    if (mCursor2.moveToFirst()) {
        do {
            ingredientName = mCursor2.getString(mCursor2.getColumnIndex("name"));
            ingredientSub = mCursor2.getString(mCursor2.getColumnIndex("sub_ingredients"));

            // create an Ingredient object in your loop and fill its
            // values
            Ingredient ingredientItem = new Ingredient();
            ingredientItem.setName(ingredientName);
            ingredientItem.setSub(ingredientSub);

            // Add your ingredient to your ingredientList
            ingredientList.add(ingredientItem);

        } while (mCursor2.moveToNext());
    }

    // Now you got a list of ingredients.
     formattedAsString = getFormattedIngredientList(ingredientList);
     ingredient.setText(Html.fromHtml(formattedAsString));

    mCursor2.close();





    Category_ID.clear();
    Category_name.clear();
    Category_image.clear();

    try {
    JSONArray jArray = new JSONArray(allergen);
    //
    for (int i = 0; i < jArray.length(); i++) {
        JSONObject object = jArray.getJSONObject(i);


        Category_ID.add((long) i);
        Category_name.add(object.getString("name"));
        Category_image.add(object.getString("image"));

    }




    JSONObject json = new JSONObject(nutrition);

final TableLayout table = (TableLayout) findViewById(R.id.table2);

                for (int j = 0; j < json.length(); j++) {

                    String s = String.valueOf(j + 1);

row3 = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row3.findViewById(R.id.localTime)).
       setText(json.getJSONObject(s).getString("qty"));
((TextView) row3.findViewById(R.id.apprentTemp)).

      setText(json.getJSONObject(s).getString("name"));

                    table.addView(row3);

                }




    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}



private String getFormattedIngredientList(ArrayList<Ingredient> ingredientList) {

    String concatProduct = "";
    for (int i = 0; i < ingredientList.size(); i++) {
        Ingredient currentIngredient = ingredientList.get(i);
                    if(currentIngredient.getSub() == null) {
                       currentIngredient.setSub("");  
                    }
        if (i == 0) {
            if ((currentIngredient.getSub() == null || 
  currentIngredient.getSub().equals(""))) {
                concatProduct = " " + "<b>" + currentIngredient.getName() + "</b>" + ", " + 
   currentIngredient.getSub();
            } else {
                concatProduct = " " + "<b>" + currentIngredient.getName() + "</b>" + ": " + 
  currentIngredient.getSub();
            }

        } else {
            if ((currentIngredient.getSub() == null || 
        currentIngredient.getSub().equals(""))) {
                if (i == ingredientList.size() - 1) {
                    concatProduct += " " + "<b>" + currentIngredient.getName() + "</b>" + 
           ". " + currentIngredient.getSub();
                } else {
                    concatProduct += " " + "<b>" + currentIngredient.getName() + "</b>" + 

         ", " + currentIngredient.getSub();
                }
            } else {
                concatProduct += " " + "<b>" + currentIngredient.getName() + "</b>" + ": " + currentIngredient.getSub();
            }
        }
    }

    return concatProduct;
}

   }


      **Following is exception:**

                 FATAL EXCEPTION: main
    java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:112)
at org.json.JSONTokener.nextValue(JSONTokener.java:90)
at org.json.JSONArray.<init>(JSONArray.java:87)
at org.json.JSONArray.<init>(JSONArray.java:103)
at com.schoollunchapp.fifthscreen.displayData(fifthscreen.java:444)
at com.schoollunchapp.fifthscreen.access$0(fifthscreen.java:377)
at com.schoollunchapp.fifthscreen$TheTask.onPostExecute(fifthscreen.java:253)
at com.schoollunchapp.fifthscreen$TheTask.onPostExecute(fifthscreen.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
4

1 に答える 1