将JSON数据加载到alertdialog到Spinner

时间:2018-12-20 17:24:35

标签: java android

我正在尝试将Json数据检索到alertdialog中的微调器中,仅在微调器处于相同活动中时才加载,但如果它在alertDialog中,则会给我这个错误:

试图在空对象引用上调用虚拟方法'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)'

package exir.exir;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
 import android.os.AsyncTask;
 import android.os.Build;
 import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
import android.support.v7.app.AlertDialog;

 import android.util.Log;
import android.view.LayoutInflater;
 import android.view.View;
  import android.widget.AdapterView;
  import android.widget.ArrayAdapter;
   import android.widget.Button;
  import android.widget.EditText;
  import android.widget.ListView;
  import android.widget.RelativeLayout;
   import android.widget.Spinner;
   import android.widget.SpinnerAdapter;
   import android.widget.Toast;

   import com.android.volley.AuthFailureError;
   import com.android.volley.Request;
    import com.android.volley.RequestQueue;
   import com.android.volley.Response;
    import com.android.volley.VolleyError;
   import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;

   import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.BufferedReader;
     import java.io.InputStream;
    import java.io.InputStreamReader;
   import java.util.ArrayList;
   import java.util.HashMap;
   import java.util.List;
    import java.util.Map;

    import exir.exir.Helpers.FormAdapter;
    import exir.exir.Helpers.PatientsAdapter;
    import exir.exir.Helpers.PricrMAdapter;
    import exir.exir.Helpers.RequestHandler;
   import exir.exir.Helpers.SharedPrefManager;
     import exir.exir.Rertofit.MyLabAPI;
    import exir.exir.Utils.Constants;
    import exir.exir.model.Form;
    import exir.exir.model.PMenus;
     import exir.exir.model.PriceM;
    import exir.exir.model.RPatient;
     import io.reactivex.android.schedulers.AndroidSchedulers;
     import io.reactivex.disposables.CompositeDisposable;
     import io.reactivex.functions.Consumer;
     import io.reactivex.schedulers.Schedulers;

   import static android.R.layout.simple_spinner_item;

  public class AddPatient extends AppCompatActivity {


private EditText patientname, gender , age , agetype , tel ,
        phone ,  total , notes  , testno , testprice , testnotes , testname1 , testno1 , testprice1 , testnotes1  ;
private Button  add ;




private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";




String labId , labpriceMenuNO ;


private static ProgressDialog mProgressDialog;
private ArrayList<PMenus> goodModelArrayList;
private ArrayList<String> names = new ArrayList<String>();

private Spinner PmSpinner;


MyLabAPI myLabAPI ;
CompositeDisposable compositeDisposable = new CompositeDisposable();

List<PriceM> pricemenilist;

ArrayAdapter<String> adapter;

ListView FormList ;
EditText editThen , edtSdt;
Button btn_sua , btn_xoa , btn_then ;
ArrayList<Form> formArrayList ;
FormAdapter formAdapter;
FloatingActionButton newTest ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_patient);



    testno = (EditText)findViewById(R.id.testno);
    testprice = (EditText)findViewById(R.id.testprice);
    testnotes = (EditText)findViewById(R.id.testnotes);


    newTest = (FloatingActionButton)findViewById(R.id. 
     newTest.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showNewTestDialog();
        }
    });







    myLabAPI = Constants.getAPI();




    add =(Button)findViewById(R.id.addPatient);








}


private void showNewTestDialog() {



    AlertDialog.Builder alertDialog = new 
    AlertDialog.Builder(AddPatient.this);
    alertDialog.setTitle("Add New Test ");
    alertDialog.setMessage("PLease fill the info  ");

    LayoutInflater inflater = this.getLayoutInflater();
    View formLayout = inflater.inflate(R.layout.newtest_layout, null);

    editThen = formLayout.findViewById(R.id.FName);
    edtSdt = formLayout.findViewById(R.id.FPrice);

    goodModelArrayList = new ArrayList<>();

    PmSpinner  = (Spinner)findViewById(R.id.testname);

    PmSpinner.setAdapter(adapter);


    PmSpinner.setOnItemSelectedListener(new 
     AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int 
          position, long id) {

            String item = parent.getItemAtPosition(position).toString() ;
            String testum = goodModelArrayList.get(position).getCity() ;
            String price = goodModelArrayList.get(position).getCountry() ;



            testnotes.setText(item);
            testno.setText(testum);
            testprice.setText(price);


        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    retrieveJSON();

    alertDialog.setView(formLayout);
    alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);


    alertDialog.setPositiveButton("YES", new 
      DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            dialogInterface.dismiss();


        //some code

        }
    });

    alertDialog.setNegativeButton("No", new 
       DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            dialogInterface.dismiss();
        }
    });

    alertDialog.show();




}














private void retrieveJSON() {


    StringRequest stringRequest = new StringRequest(
            Request.Method.GET,
            URLstring,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    Log.d("strrrrr", ">>" + response);

                    try {

                        JSONObject obj = new JSONObject(response);
                         goodModelArrayList = new ArrayList<>();

                            JSONArray dataArray  = obj.getJSONArray("data");

                            for (int i = 0; i < dataArray.length(); i++) {



                                PMenus playerModel = new PMenus();

                                JSONObject dataobj = 
                       dataArray.getJSONObject(i);




                           playerModel.setName(dataobj.getString("name"));


                    playerModel.setCountry(dataobj.getString("country"));

                        playerModel.setCity(dataobj.getString("city"));

                       playerModel.setImgURL(dataobj.getString("imgURL"));



                                goodModelArrayList.add(playerModel);



                            }
                            for (int i = 0; i < goodModelArrayList.size(); 
                                 i++){

                  names.add(goodModelArrayList.get(i).getName().toString());
                            }

                            ArrayAdapter<String> spinnerArrayAdapter = new 
          ArrayAdapter<String>(AddPatient.this, simple_spinner_item, names);

 spinnerArrayAdapter.setDropDownViewResource(
 android.R.layout.simple_spinner_dropdown_item); // The drop down view
                            PmSpinner.setAdapter(spinnerArrayAdapter);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //displaying the error in toast if occurrs
                    Toast.makeText(getApplicationContext(), 
  error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

    // request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);


}

2 个答案:

答案 0 :(得分:0)

尝试一下.....

JSONObject c = JSONfunctions.getJSONfromURL("http://192.168.1.104/OnlineTicketBooking/book_now1.php?movieid='72'");

try {
    JSONArray jarray = c.getJSONArray("offer_detail");
    ArrayList<String> xyz= new ArrayList<String>();
    for(int i = 0; i < jarray.length(); i++){
    JSONArray timeArray = jarray.getJSONObject(i).getJSONArray("showtime");
    for(int j = 0; j < timeArray .length(); j++){
        xyz.add(timeArray .getString(j));
        Log.d("get value",timeArray .getString(j));`enter code here`
    } 
}

答案 1 :(得分:0)

尝试类似以下代码:

public class SubMenu extends AppCompatActivity {


    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "id";
    static String COUNTRY = "name";

    static String FLAG = "image";
    Integer i = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_sub_menu);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        String SelectedId = getIntent().getStringExtra("id");


        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        // Get the view from listview_main.xml

        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> implements AdapterView.OnItemClickListener {

        // @Override
        //  protected void onPreExecute() {
        //  super.onPreExecute();
        // Create a progressdialog
        //   mProgressDialog = new ProgressDialog(SubMenu.this);
        // Set progressdialog title
        //   mProgressDialog.setTitle("Categories of Main categories.....");
        // Set progressdialog message
        //  mProgressDialog.setMessage("Loading...");
        //  mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        //  mProgressDialog.show();
        // }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonarray = JsonFunctions
                    .getJSONfromURL("http://cloud.granddubai.com/broccoli/menu_typeitem.php?id=" + getIntent().getStringExtra("id"));
            try {
                // Locate the array name in JSON
//                    jsonarray = jsonobject.getJSONArray("main_menu_items");


                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();

                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    // map.put("id", jsonobject.getString("id"));
                    map.put("name", jsonobject.getString("name"));

                    map.put("image", jsonobject.getString("image"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.list1);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(SubMenu.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(this);
            // Close the progressdialog
            // mProgressDialog.dismiss();
        }


        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long rowId) {


            final AlertDialog customDialog = new AlertDialog.Builder(SubMenu.this).create();
            final LayoutInflater inflater = getLayoutInflater();
            final View dialogView = inflater.inflate(R.layout.popup
                    , null);
            customDialog.setView(dialogView);
            // set the custom customDialogimation components - text, image and button
            final TextView tvDistance = (TextView) dialogView.findViewById(R.id.h2);

            //  crust.setOnItemSelectedListener(this);
// public void addListenerOnSpinnerItemSelection() {


            final Button ok = (Button) dialogView.findViewById(R.id.ok);
            ok.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    customDialog.dismiss();


                }
            });


            final Button cncl = (Button) dialogView.findViewById(R.id.canc);
            cncl.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    customDialog.dismiss();


                }
            });


            Button _decrease = (Button) dialogView.findViewById(R.id.incr);
            Button _increase = (Button) dialogView.findViewById(R.id.decr);
            Spinner spinner1 = (Spinner) dialogView.findViewById(R.id.crust);
            Spinner spinner2 = (Spinner) dialogView.findViewById(R.id.adson);
            ArrayList<String> alspinner1 = new ArrayList<>();
            ArrayList<String> alspinner2 = new ArrayList<>();


            final String[] _spvalue1 = getResources().getStringArray(R.array.Crust_array);
            final String[] _spvalue2 = getResources().getStringArray(R.array.AddsOn_array);
            for (int i = 0; i < _spvalue1.length; i++) {
                alspinner1.add(_spvalue1[i]);
            }
            for (int i = 0; i < _spvalue2.length; i++) {
                alspinner2.add(_spvalue2[i]);
            }
            ArrayAdapter<String> adapter1 = new ArrayAdapter<>(dialogView.getContext(), android.R.layout.simple_spinner_item, alspinner1);
            ArrayAdapter<String> adapter2 = new ArrayAdapter<>(dialogView.getContext(), android.R.layout.simple_spinner_item, alspinner2);

            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner1.setAdapter(adapter1);
            spinner2.setAdapter(adapter2);

            final TextView _value = (TextView) dialogView.findViewById(R.id.value);
            i = Integer.parseInt(_value.getText().toString());


            _decrease.setOnClickListener(new View.OnClickListener() {


                public void onClick(View v) {
                    String _stringVal;
                    Log.d("src", "Decreasing value...");
                    if (i > 0) {
                        i = i - 1;
                        _stringVal = String.valueOf(i);
                        _value.setText(_stringVal);
                    } else {
                        Log.d("src", "Value can't be less than 0");
                    }

                }
            });

            _increase.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    String _stringVal;

                    Log.d("src", "Increasing value...");
                    i = i + 1;
                    _stringVal = String.valueOf(i);
                    _value.setText(_stringVal);
                }
            });
            customDialog.show();
        }


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

我为我的应用程序尝试了相同的概念,并且此代码在这里起作用。您可以从中寻求帮助。谢谢!!