繁体   English   中英

如何在Android的微调器中显示默认列表

[英]how to show default list in spinner in android

最近,我开发了一个应用程序。 这样,将从MySQL数据库中的值检索到微调器中。 问题是当不存在Internet时它崩溃。 我的意图是,如果不存在互联网,请显示默认值。 否则,如果互联网可用,则显示MySQL数据库中的值。

public class MilkProduction extends AppCompatActivity implements Spinner.OnItemSelectedListener{
    private EditText quantity;
    private Button submit, cancel;
    private TextView date_time;
    Calendar calander;
    SimpleDateFormat simpleDateFormat;
    String time;
    private AutoCompleteTextView animal_id;
    private List<Animal> fruits ;
    Boolean isInternetPresent = false;
    private ConnectionDetector cd;
    private Spinner spinner1;
    private String shift_id;
    private String product;
     String shiftid="",intime="",outtime="";
    //JSON Array
    private JSONArray result;
    //An ArrayList for Spinner Items
    private ArrayList<String> students;
private  Animal item ;
    private Animal animal=new Animal();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setContentView(R.layout.milk_production);

        animal_id = (AutoCompleteTextView) findViewById(R.id.edt_animal_id);
        quantity = (EditText) findViewById(R.id.edt_milkproduction_quan);
        date_time = (TextView) findViewById(R.id.txt_timt_date_year);
        submit = (Button) findViewById(R.id.btn_prodc_submit);


        calander = Calendar.getInstance();
        simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
        time = simpleDateFormat.format(calander.getTime());
        date_time.setText(time);
        date_time.setTextSize(15);

        students = new ArrayList<String>();

        spinner1 = (Spinner) findViewById(R.id.spinner);

        spinner1.setOnItemSelectedListener(this);



        cd = new ConnectionDetector(getApplicationContext());


        //Calling the method that will fetch data
        proautocomplete();

        prodropdown();

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isInternetPresent = cd.isConnectingToInternet();


                // check for Internet status
                if (isInternetPresent) {

                     insertUser();
                   }
               else{

                    showAlertDialog(MilkProduction.this, "Internet not available",
                            "Internet is not available in this device", false);
                }
            }
        });

 }

    private void prodropdown() {
        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(Config.ROOT_URL) //Setting the Root URL
                .build(); //Finally building the adapter

        //Creating object for our interface
        AnimalAPI api = adapter.create(AnimalAPI.class);
        api.insertUser1( new Callback<Response>() {


            @Override
            public void success(Response response, Response response2) {

               String detailsString = Others.getStringFromRetrofitResponse(response);


                try {

                    //Parsing the fetched Json String to JSON Object
                    JSONObject  j = new JSONObject(detailsString);

                    //Storing the Array of JSON String to our JSON Array
                    result = j.getJSONArray(Config.JSON_ARRAY);

                    //Calling method getStudents to get the students from the JSON Array
                    getStudents(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }




            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void getStudents(JSONArray j) {

        //Traversing through all the items in the json array
        for(int i=0;i<j.length();i++){
            try {
                //Getting json object
                JSONObject json = j.getJSONObject(i);

                //Adding the name of the student to array list
                students.add(json.getString(Config.TAG_USERNAME));



            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //Setting adapter to show the items in the spinner
        spinner1.setAdapter(new ArrayAdapter<String>(MilkProduction.this, android.R.layout.simple_spinner_dropdown_item, students));

    }



    //Method to get student name of a particular position
    private String getShiftid(int position){
        String name="";
        try {
            //Getting object of given index
            JSONObject json = result.getJSONObject(position);

            //Fetching name from that object
         //   name = json.getString(Config.TAG_NAME);

            name = animal.setShiftid(json.getString(Config.TAG_NAME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Returning the name
        return name;
    }

    //Doing the same with this method as we did with getName()
    private String getIntime(int position){
        String course="";
        try {
            JSONObject json = result.getJSONObject(position);
         //   course = json.getString(Config.TAG_COURSE);

            course= animal.setIntime(json.getString(Config.TAG_COURSE));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return course;
    }

    //Doing the same with this method as we did with getName()
    private String getOuttime(int position){
        String session="";
        try {
            JSONObject json = result.getJSONObject(position);
          //  session = json.getString(Config.TAG_SESSION);

            session=  animal.setOuttime(json.getString(Config.TAG_SESSION));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return session;
    }


    public void onItemSelected(AdapterView<?> parent, View view, int position,
                               long id) {
        // TODO Auto-generated method stub
        String spin = parent.getItemAtPosition(position).toString();

        //Setting the values to textviews for a selected item

        shiftid=(getShiftid(position));
        intime=(getIntime(position));
        outtime=(getOuttime(position));



    }



    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub
          shiftid="";
           intime="";
          outtime="";

    }


    private void insertUser() {
//While the app fetched data we are displaying a progress dialog
        final ProgressDialog loading = ProgressDialog.show(this,"Loading","Please wait...",false,false);

        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(Config.ROOT_URL) //Setting the Root URL
                .build(); //Finally building the adapter

        //Creating object for our interface
        AnimalAPI api = adapter.create(AnimalAPI.class);


        api.insertUser(
                animal_id.getText().toString(),
                quantity.getText().toString(),
                date_time.getText().toString(),

                spinner1.getSelectedItem().toString(),
                " ",
                shiftid,
                intime,
                outtime,
                new Callback<Response>() {
                    @Override
                    public void success(Response result, Response response) {
                        //On success we will read the server's output using bufferedreader
                        loading.dismiss();
                        //Creating a bufferedreader object
                        BufferedReader reader = null;

                        //An string to store output from the server
                        String output = "";

                        try {
                            reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

                            //Reading the output in the string
                            output = reader.readLine();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        //Displaying the output as a toast
                        Toast.makeText(MilkProduction.this, output, Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        //If any error occured displaying the error as toast
                        loading.dismiss();
                        Toast.makeText(MilkProduction.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }

        );

    }

}

布局:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/mm"

    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="@dimen/dairy_layout_height"
        android:orientation="vertical"
        android:layout_gravity="center_horizontal"
        android:gravity="center_vertical|center_horizontal"
        android:layout_marginTop="25dp"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:background="@drawable/corner3"
        >
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="13dp"
            android:layout_gravity="center"
            >
            <TextView
                android:id="@+id/heder"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Milk Production"
                android:layout_gravity="center"
                android:gravity="center"
                android:layout_margin="5dp"
                android:textSize="25sp"
                android:textColor="@color/textcolour"
                />

            <View
                android:layout_width="250dp"
                android:layout_height="2dip"
                android:background="#023e64"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_margin="13dp"
            android:layout_gravity="left"
            android:layout_weight="1"
            >
            <TextView
                android:id="@+id/txt_animal_shfit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Shift                       : "
                android:textSize="20sp"
                android:textColor="@color/textcolour"
                android:layout_weight="0.40"
                android:gravity="left"
                android:layout_marginTop="12dp"
                />
            <Spinner
                android:layout_width="160dp"
                android:layout_height="50dp"
                android:id="@+id/spinner"
                android:layout_gravity="center_horizontal"
                android:spinnerMode="dialog"
                android:prompt="@string/shift_prompt"
                android:background="@android:drawable/btn_dropdown"
                android:entries="@array/android_dropdown_arrays1"
                style="@android:style/Widget.Holo.Light.Spinner"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_margin="13dp"
            android:layout_gravity="left"
            android:layout_weight="1"
            >
            <TextView
                android:id="@+id/txt_animal_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Animal                   : "
                android:textSize="20sp"
                android:textColor="@color/textcolour"
                android:layout_weight="0.40"
                android:gravity="left"
                />

            <AutoCompleteTextView
                android:id="@+id/edt_animal_id"
                android:layout_width="160dp"
                android:layout_height="50dp"
                android:background="@drawable/corner1"
                android:layout_weight="0.60"
                android:layout_alignParentLeft="true"
                android:ems="10"
                android:text="">

            </AutoCompleteTextView>
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_margin="13dp"
            android:layout_gravity="left"
            android:layout_weight="1"
            >
            <TextView
                android:id="@+id/txt_milk"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Quantity                 : "
                android:textSize="20sp"
                android:textColor="@color/textcolour"
                android:layout_weight="0.40"
                android:gravity="left"
                />
            <EditText
                android:id="@+id/edt_milkproduction_quan"
                android:layout_width="121dp"
                android:layout_height="50dp"

                android:background="@drawable/corner1"
                android:layout_weight="0.60"
                android:inputType="number"
                android:ems="10"
                />
            <TextView
                android:id="@+id/txt_milk_quantity"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" Lts."
                android:textSize="20sp"
                android:textColor="@color/textcolour"
                android:layout_weight="0.40"
                android:gravity="right"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_margin="13dp"
            android:layout_gravity="left"
            >
            <TextView

            android:id="@+id/btn_prodc_submit"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="Submit"
            android:textSize="@dimen/button_sub_txt_size"
            android:layout_margin="@dimen/button_layout_margin"
            android:background="@drawable/btnbackground"
            android:textColor="@color/textcolour"
            />


    </LinearLayout>
    </LinearLayout>

</ScrollView>

我认为应该尝试类似的操作以在没有互联网的情况下显示默认值,否则获取sql的值

if(cd.isConnectingToInternet()){
     prodropdown();
}else{
     //Setting adapter to show the items in the spinner
     List<String> spinnerArray =  new ArrayList<String>();
     spinnerArray.add("default value 1");
     spinnerArray.add("default value 2");
     spinnerArray.add("default value 3");

     ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    this, android.R.layout.simple_spinner_item, spinnerArray);

     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

     spinner1.setAdapter(adapter);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM