0

我有这样的活动:

图片1

我从 SQLite 加载列表,并使用上下文菜单选择列表:

图片2

我选择更新以显示活动。

问题是,当 i=我选择列表并根据数据列表在上下文菜单中选择更新时,如何显示不同的链接或加载活动?

例子:

在备注字段中,我有三组数据:“Serangan Hama”、“Pestisida”和“Bencana Alam”。

我有每个数据的 3 个活动表格。

如果我选择“Bencana Alam”,那么它将显示活动 BencanaAlam.java

如果我选择“Pestisida”,那么它将显示活动 Pestisida.java

这是活动代码:

public class MainListKeliling extends ListActivity {
      private LocationManager lm;
      String[] remark = { "Bencana Alam", "Serangan Hama", "Pestisida" };
      Spinner spinRemark;
      private LocationListener locListener;
      private TextView latTxt, lonTxt;

      Intent intent = null;
      private static final int ADD_ID = Menu.FIRST+1;
      private static final int DELETE_ID = Menu.FIRST+3;
      private static final int UPDATE_ID = Menu.FIRST+4;
      private static final int DETAIL_ID = Menu.FIRST+5;
      private static final int CANCEL = Menu.FIRST+6;
      public static final int SHOW_SUB_ACTIVITY_VIEW=3;
      public static final int DIALOG_DATE_AWAL = 5;
        public static final int DIALOG_DATE_AKHIR = 6;
      private DatabaseHelper db=null;
      private DatabaseHelper ds=null;
      private Cursor constantsCursor=null;

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lyt_banner_keliling);
        //ds = new DatabaseHelper(getApplicationContext());
        //ds.loadAll();

        db=new DatabaseHelper(this);
        constantsCursor=db
                          .getReadableDatabase()
                          .rawQuery("SELECT _ID, alamat, tglb, tipe "+
                                    "FROM keliling ORDER BY _ID",
                                    null);

        ListAdapter adapter=new SimpleCursorAdapter(this,
                              R.layout.lyt_list_keliling, constantsCursor,
                              new String[] {
                                            DatabaseHelper.ID,
                                            DatabaseHelper.ALAMAT,
                                            DatabaseHelper.TYPE,
                                            DatabaseHelper.TANGGAL_AKHIR
                                            },
                              new int[] {R.id.id, R.id.alamat, R.id.remark, R.id.tglakhir});

        setListAdapter(adapter);
        registerForContextMenu(getListView());

        Button button = (Button) findViewById(R.id.btnKembali);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                LogOut();
                setResult(RESULT_OK, null);
                finish();
            }
        });

        button = (Button) findViewById(R.id.btnDataBaru);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                add();
            }
        });

      }// onCreate

      private void LogOut(){

        }//LogOut

      @Override
      public void onDestroy() {
        super.onDestroy();

        constantsCursor.close();
        db.close();
      }





      @Override
      public void onCreateContextMenu(ContextMenu menu, View v,
                                        ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(Menu.NONE, DETAIL_ID, Menu.NONE, "Detail");
        menu.add(Menu.NONE, UPDATE_ID, Menu.NONE, "Update");
        menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete");
        menu.add(Menu.NONE, CANCEL, Menu.NONE, "Back")

            .setAlphabeticShortcut('d');
      }

      @Override
      public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case DETAIL_ID:
            AdapterView.AdapterContextMenuInfo info=
              (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

            detail(info.id);
            return(true);

        case DELETE_ID:
            AdapterView.AdapterContextMenuInfo infoDetail=
              (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

            delete(infoDetail.id);
            return(true);

          case UPDATE_ID:
              intent = new Intent(MainListKeliling.this, UpdateKeliling.class);
                startActivityForResult(intent, SHOW_SUB_ACTIVITY_VIEW);
              return(true);
        }

        return(super.onOptionsItemSelected(item));
      }


      private LocationManager lman;
      private LocationListener locaListener;
      private TextView latTxtt, lonTxtt;
      private EditText tvDisplayDateAwal, tvDisplayDateAkhir;
      private DatePicker dpResult;
      private int year;
      private int month;
      private int day;

        private void add() {
        LayoutInflater inflater=LayoutInflater.from(this);
        View addView=inflater.inflate(R.layout.lyt_add_keliling, null);
        latTxtt = (TextView) addView.findViewById(R.id.latitudeTxtt);
        lonTxtt = (TextView) addView.findViewById(R.id.longitudeTxtt);

        lman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locaListener = new MyLocationListenerDialog();
        lman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10,locaListener);

        tvDisplayDateAwal = (EditText) addView.findViewById(R.id.tglawal);
        tvDisplayDateAkhir = (EditText) addView.findViewById(R.id.tglakhir);
        dpResult = (DatePicker) addView.findViewById(R.id.dpResult);
        dpResult.setVisibility(View.GONE);

        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        // set current date into textview
        tvDisplayDateAkhir.setText(new StringBuilder()
                // Month is 0 based, just add 1
                .append(day).append("-").append(month + 1).append("-")
                .append(year).append(" "));

        // set current date into datepicker
        dpResult.init(year, month, day, null);
        Date date1 = (Date) new Date(dpResult.getYear() - 1900,
                dpResult.getMonth(), dpResult.getDayOfMonth());
        SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
        String dateString = dates.format(date1);
        tvDisplayDateAkhir.setText(dateString);

        View showDlgAwal = addView.findViewById(R.id.tglawal);
        showDlgAwal.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                showDialog(DIALOG_DATE_AWAL);
            }
        });

        View showDlgAkhir = addView.findViewById(R.id.tglakhir);
        showDlgAkhir.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                showDialog(DIALOG_DATE_AKHIR);
            }
        });

        //spinner
        // buat spinner manual Petak
        Spinner spinRemark = (Spinner) addView.findViewById(R.id.tipe);

        ArrayAdapter<String> aa = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, remark);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinRemark.setAdapter(aa);

        spinRemark = (Spinner) addView.findViewById(R.id.tipe);
        spinRemark.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
                //Toast.makeText(CPupukApp.this, "Anda Memilih: " + manufaktur[position],Toast.LENGTH_LONG).show();
            }

            public void onNothingSelected(AdapterView<?> parent) {

            }


            });

        final DialogWrapper wrapper=new DialogWrapper(addView);

        new AlertDialog.Builder(this)
          .setTitle(R.string.add_title)
          .setView(addView)
          .setPositiveButton(R.string.ok,
                              new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,
                                  int whichButton) {
              processAdd(wrapper);
              lman.removeUpdates(locaListener);
            }
          })
          .setNegativeButton(R.string.cancel,
                              new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,
                                  int whichButton) {
              // stop gps
                lman.removeUpdates(locaListener);
            }
          })
          .show();
      }//akhir fungsi add

        public Dialog onCreateDialog(int id) {
            switch (id) {
            case (DIALOG_DATE_AWAL):
                return new DatePickerDialog(this, datePickerListenerAwal, year,
                        month, day);

            case (DIALOG_DATE_AKHIR):
                return new DatePickerDialog(this, datePickerListenerAkhir, year,
                        month, day);
            }
            return null;
        }// onCreateDialog

        // isi dialog awal
        private DatePickerDialog.OnDateSetListener datePickerListenerAwal = new DatePickerDialog.OnDateSetListener() {

            // when dialog box is closed, below method will be called.
            public void onDateSet(DatePicker view, int selectedYear,
                    int selectedMonth, int selectedDay) {
                year = selectedYear;
                month = selectedMonth;
                day = selectedDay;

                // set selected date into textview
                tvDisplayDateAwal.setText(new StringBuilder().append(day)
                        .append("-").append(month + 1).append("-").append(year)
                        .append(" "));

                // set selected date into datepicker also
                dpResult.init(year, month, day, null);

                Date date1 = (Date) new Date(dpResult.getYear() - 1900,
                        dpResult.getMonth(), dpResult.getDayOfMonth());
                SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
                String dateString = dates.format(date1);
                tvDisplayDateAwal.setText(dateString);
            }
        };

        // isi dialog akhir
        private DatePickerDialog.OnDateSetListener datePickerListenerAkhir = new DatePickerDialog.OnDateSetListener() {

            // when dialog box is closed, below method will be called.
            public void onDateSet(DatePicker view, int selectedYear,
                    int selectedMonth, int selectedDay) {
                year = selectedYear;
                month = selectedMonth;
                day = selectedDay;

                // set selected date into textview
                tvDisplayDateAkhir.setText(new StringBuilder().append(day)
                        .append("-").append(month + 1).append("-").append(year)
                        .append(" "));

                // set selected date into datepicker also
                dpResult.init(year, month, day, null);

                Date date1 = (Date) new Date(dpResult.getYear() - 1900,
                        dpResult.getMonth(), dpResult.getDayOfMonth());
                SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
                String dateString = dates.format(date1);
                tvDisplayDateAkhir.setText(dateString);
            }
        };

      private class MyLocationListenerDialog implements LocationListener {
            @Override
            public void onLocationChanged(Location loc) {
                // TODO Auto-generated method stub
                if (loc != null) {
                    latTxtt.setText(String.valueOf(loc.getLatitude()));
                    lonTxtt.setText(String.valueOf(loc.getLongitude()));
                }
            }

            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub

            }

        }

      private void loadUser(View view) {

            // Creating adapter for spinner


        }

      private void detail(final long rowId) {
            if (rowId>0) {
                LayoutInflater inflater=LayoutInflater.from(this);
                View addView=inflater.inflate(R.layout.detail_keliling, null);

                final DialogWrapper wrapper=new DialogWrapper(addView);
                TextView idDt = (TextView) addView.findViewById(R.id.idDetail);
                TextView codeTxtDt = (TextView) addView.findViewById(R.id.codeDetail);
                TextView alamatTxtDt = (TextView) addView.findViewById(R.id.alamatDetail);
                TextView batasTxtDt = (TextView) addView.findViewById(R.id.batasDetail);
                TextView latTxtDt = (TextView) addView.findViewById(R.id.latDetail);
                TextView lonTxtDt = (TextView) addView.findViewById(R.id.lonDetail);
                TextView luasTxtDt = (TextView) addView.findViewById(R.id.luasDetail);
                TextView tglAwalTxtDt = (TextView) addView.findViewById(R.id.tglAwalDetail);
                TextView tglAkhirTxtDt = (TextView) addView.findViewById(R.id.tglAkhirDetail);
                TextView remarkTxtDt = (TextView) addView.findViewById(R.id.tipe);
                //View editTextHidden = (EditText) findViewById(R.id.txtHidden);
                // database handler
                DatabaseHelper db = new DatabaseHelper(getApplicationContext()); 
                // Spinner Drop down elements
                SQLiteDatabase dbs = db.getReadableDatabase();

                Cursor cursor = dbs.rawQuery("SELECT * FROM keliling where _ID=" +rowId+"", null);
              if (cursor.moveToFirst()) {
                 do {
                    String noId=cursor.getString(0); // Here you can get data from table and stored in string if it has only one string.
                    String code=cursor.getString(1);
                    String alamat=cursor.getString(2);
                    String batas=cursor.getString(3);
                    String lat=cursor.getString(4);
                    String lon=cursor.getString(5);
                    String luas=cursor.getString(6);
                    String tglAwal=cursor.getString(7);
                    String tglAkhir=cursor.getString(8);
                    String remark=cursor.getString(9);

                    idDt.setText(noId);
                    codeTxtDt.setText(code);
                    alamatTxtDt.setText(alamat);
                    batasTxtDt.setText(batas);
                    latTxtDt.setText(lat);
                    lonTxtDt.setText(lon);
                    luasTxtDt.setText(luas);
                    tglAwalTxtDt.setText(tglAwal);
                    tglAkhirTxtDt.setText(tglAkhir);
                    remarkTxtDt.setText(remark);

                 } while (cursor.moveToNext());
              }
              if (cursor != null && !cursor.isClosed()) {
                 cursor.close();
              }
              if(db!=null)
              {
                  db.close();
              }
              new AlertDialog.Builder(this)
                .setTitle(R.string.detail_title)

                .setView(addView)
                .setPositiveButton(R.string.ok,
                                    new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog,
                                        int whichButton) {
                  // ignore, just dismiss
                  }
                })
                .show();
            }
          }

      private void delete(final long rowId) {
        if (rowId>0) {
          new AlertDialog.Builder(this)
            .setTitle(R.string.delete_title)
            .setPositiveButton(R.string.ok,
                                new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog,
                                    int whichButton) {
                processDelete(rowId);
              }
            })
            .setNegativeButton(R.string.cancel,
                                new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog,
                                    int whichButton) {
              // ignore, just dismiss
              }
            })
            .show();
        }
      }

      private void processAdd(DialogWrapper wrapper) {
        ContentValues values=new ContentValues(2);

        values.put(DatabaseHelper.CODE, wrapper.getCode());
        values.put(DatabaseHelper.ALAMAT, wrapper.getAlamat());
        values.put(DatabaseHelper.BATAS, wrapper.getBatas());
        values.put(DatabaseHelper.LAT, wrapper.getLat());
        values.put(DatabaseHelper.LON, wrapper.getLon());
        values.put(DatabaseHelper.LUAS, wrapper.getLuas());
        values.put(DatabaseHelper.TANGGAL_AWAL, wrapper.getTglA());
        values.put(DatabaseHelper.TANGGAL_AKHIR, wrapper.getTglB());
        values.put(DatabaseHelper.TYPE, wrapper.getRemark());

        db.getWritableDatabase().insert("keliling", DatabaseHelper.ALAMAT, values);
        constantsCursor.requery();
      }

      private void processDelete(long rowId) {
        String[] args={String.valueOf(rowId)};

        db.getWritableDatabase().delete("keliling", "_ID=?", args);
        constantsCursor.requery();
      }

      class DialogWrapper {
        EditText codeField=null;
        EditText alamatField=null;
        EditText batasField=null;
        EditText luasField=null;
        EditText tglAField=null;
        EditText tglBField=null;
        TextView latField=null;
        TextView lonField=null;
        Spinner remark=null;
        View base=null;

        DialogWrapper(View base) {
          this.base=base;
          tglBField=(EditText)base.findViewById(R.id.tglakhir);
        }

        String getCode() {
            return(getCodeField().getText().toString());
          }

        String getAlamat() {
          return(getAlamatField().getText().toString());
        }

        String getBatas() {
            return(getBatasField().getText().toString());
          }

        String getLuas() {
            return(getLuasField().getText().toString());
          }

        String getTglA() {
            return(getTglAField().getText().toString());
          }

        String getTglB() {
          return(getTglBField().getText().toString());
        }

        String getLat() {
            return(getLatField().getText().toString());
          }

        String getLon() {
            return(getLonField().getText().toString());
          }

        String getRemark(){
            return(getRemarkField().getSelectedItem().toString());
        }
        //String spinnerMan=((Spinner) remark).getSelectedItem().toString();

        private EditText getCodeField() {
            if (codeField==null) {
              codeField=(EditText)base.findViewById(R.id.code);
            }
            return(codeField);
          }

        private EditText getAlamatField() {
          if (alamatField==null) {
              alamatField=(EditText)base.findViewById(R.id.alamat);
          }

          return(alamatField);
        }

        private EditText getBatasField() {
            if (batasField==null) {
              batasField=(EditText)base.findViewById(R.id.batas);
            }

            return(batasField);
          }

        private TextView getLatField() {
            if (latField==null) {
              latField=(TextView)base.findViewById(R.id.latitudeTxtt);
            }

            return(latField);
          }

        private TextView getLonField() {
            if (lonField==null) {
             lonField=(TextView)base.findViewById(R.id.longitudeTxtt);
            }

            return(lonField);
          }

        private EditText getLuasField() {
            if (luasField==null) {
              luasField=(EditText)base.findViewById(R.id.luas);
            }

            return(luasField);
          }

        private EditText getTglAField() {
            if (tglAField==null) {
                tglAField=(EditText)base.findViewById(R.id.tglawal);
            }

            return(tglAField);
          }

        private EditText getTglBField() {
          if (tglBField==null) {
              tglBField=(EditText)base.findViewById(R.id.tglakhir);
          }

          return(tglBField);
        }

        private Spinner getRemarkField() {
              if (remark==null) {
                  remark=(Spinner)base.findViewById(R.id.tipe);
              }

              return(remark);
            }
      }
    }

怎么做?

4

1 回答 1

2

所以基本上你想从 onContextItemSelected() 中的 List 中获取选定的项目。

// Here's how you can get the correct item in onContextItemSelected()
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Object item = getListAdapter().getItem(info.position);

由于您使用 SimpleCursorAdapter 作为 ListAdapter,因此上面返回的对象是 Cursor。

    Cursor c = (Cursor) item;
    String type = c.getString(c.getColumnIndex(DatabaseHelper.TYPE));
    Intent intent;

    if ("Bencana Alam".equals(type)) {
        intent = new Intent(MainListKeliling.this, BencanaAlam.class);
    } else if ("Pestisida".equals(type)) {
        intent = new Intent(MainListKeliling.this, Pestisida.class);
    }
    startActivityForResult(intent, SHOW_SUB_ACTIVITY_VIEW);
于 2013-03-04T03:43:51.207 回答