当我点击listeview项目时,我无法从db获取数据

时间:2015-09-03 05:14:20

标签: android

我无法从列表视图的项目中获取对应数据。 我在这里使用短信和电子邮件模板。当我点击短信或任何电子邮件列表视图项时,它将在编辑文本格式数据库中打开,然后可以更新数据然后存储。对应于电子邮件或短信.i为数据库创建字段为电子邮件和短信模板,如 id,template_name,message,template_code(0,1),即使用短信或电子邮件指定在i上。 这里有三个活动ManageEmailTemplate,ManageSmsTemplate,用于下一个活动,即SMSTemplateEdit

ManageEmailTemplate.java

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

        setContentView(R.layout.manage_email_template);

        //-------------------------
        dba = new MyDB(this);
        dba.open();

        mQuery = "Select " +
                       Constants.KEY_ID_GREET + "," +
                       Constants.GREETING_NAME + "," +
                       Constants.GREETING_MESSAGE+ "," +
                       Constants.KEY_ID_SETUP_GREET  +
                       " from " + Constants.TABLE_NAME_GREETINGS +
                       " where " + Constants.KEY_ID_SETUP_GREET + " = " + Constants.EMAIL_CODE;

        c = dba.getResults( mQuery );
        startManagingCursor(c); 

        String[] resultColumns;

        if( c != null && c.moveToFirst()){      

        }

        int[] textviews = new int[] {android.R.id.text1};
        resultColumns = new String[] { Constants.GREETING_NAME};

        mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, resultColumns, textviews);

        this.setListAdapter(mAdapter);
        getListView().setTextFilterEnabled(true);

        //dba.close();

        //-------------------------

        // Create Email Templates
        //setup Create Email Templates Listener       
        Button createEmailTemplatesButton = (Button) findViewById(R.id.create_email_template_button);
            createEmailTemplatesButton.setOnClickListener(new OnClickListener(){
                public void onClick(View view){
                    showCreateEmailTemplate();
                }
        });  


    }

    private void showCreateEmailTemplate(){
        Intent i = new Intent(this, CreateNewTemplate.class);
        i.putExtra("template_type","email");
        //startActivity(i);

        startActivityForResult(i, mRequestCode);
    }



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

        super.onItemClick(parent, v, position, id);

     final Cursor c = (Cursor) mAdapter.getItem(position);

     String name = c.getString(c.getColumnIndex( Constants.GREETING_NAME ));
    final int template_id = c.getInt(c.getColumnIndex( Constants.KEY_ID_GREET ));
     temp_id=String.valueOf(template_id);


     goForEdit();
     //confirm
Toast.makeText(this,
        "Name :"+name+"  id : " +template_id , Toast.LENGTH_LONG)
        .show();    
     }

    public void goForEdit(){
        Intent launchSMSTempEdit = new Intent(
                ManageEmailTemplate.this,
                            EmailSMSTempEdit.class);

launchSMSTempEdit.getExtras().get("selection"));
    //        startActivity(launchSMSTempEdit);

                //  Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
//                  startActivity(launchSMSTempEdit);

                    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
                     //now get Editor
                     SharedPreferences.Editor editor = sharedPref.edit();
                     //put your value
                     editor.putString("Temp_id", temp_id);
                     editor.putString("template_type", "email");
                     //commits your edits
                     editor.commit();   

                     startActivity(launchSMSTempEdit);

    }

}


ManageSMSTemplate.java


public class ManageSMSTemplate extends
        ActionBarListActivity {

    private MyDB dba;

    private Cursor c;
    String temp_id;

    private SimpleCursorAdapter mAdapter;

    private int mRequestCode = 0000;
ListView lst;
    private String mQuery;


    /** Called when the activity is first created. */
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        lst =(ListView)findViewById(android.R.id.list);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.manage_sms_template);

        // -------------------------
        dba = new MyDB(this);
        dba.open();

        mQuery = "Select " + Constants.KEY_ID_GREET + ","
                + Constants.GREETING_NAME + ","
                + Constants.GREETING_MESSAGE + ","
                + Constants.KEY_ID_SETUP_GREET + " from "
                + Constants.TABLE_NAME_GREETINGS
                + " where " + Constants.KEY_ID_SETUP_GREET
                + " = " + Constants.SMS_CODE;

        c = dba.getResults(mQuery);
        startManagingCursor(c);

        String[] resultColumns;

        if (c != null && c.moveToFirst()) {

        }

        int[] textviews = new int[] { android.R.id.text1 };
        resultColumns = new String[] { Constants.GREETING_NAME };
        mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1, c,
                resultColumns, textviews);
        this.setListAdapter(mAdapter);
        getListView().setTextFilterEnabled(true);

        // -------------------------

        // Create sms Templates
        // setup Create SMS Templates Listener
        Button createSMSTemplatesButton = (Button) findViewById(R.id.create_sms_template_button);
        createSMSTemplatesButton
                .setOnClickListener(new OnClickListener() {

                    public void onClick(View view)
                    {

                        showCreateSMSTemplate();
                    }
                });

    }

    private void showCreateSMSTemplate()
    {

        Intent i = new Intent(this, CreateNewTemplate.class);
        i.putExtra("template_type", "sms");
        startActivityForResult(i, mRequestCode);
    }

    @Override
    protected void onActivityResult(int requestCode,
            int resultCode, Intent data)
    {

        super.onActivityResult(requestCode, resultCode,
                data);

        Log.v("Crash",
                "Returned from template creation in SMStemplate Manager");

        if (mAdapter == null)
            Log.d("Crash", "SMS-Manager - mAdapter is NULL");
        else
            Log.d("Crash",
                    "SMS-Manager - mAdapter is NOT Null");

        if (requestCode == mRequestCode) {
            if (resultCode == RESULT_OK) {
                if (mAdapter.getCursor() != null)
                    mAdapter.getCursor().requery();
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onDestroy()
    {

        dba.close();
        super.onDestroy();
    }

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

        super.onItemClick(parent, v, position, id);

        final Cursor c = (Cursor) mAdapter
                .getItem(position);

        String name = c.getString(c
                .getColumnIndex(Constants.GREETING_NAME));
        final int template_id = c.getInt(c
                .getColumnIndex(Constants.KEY_ID_GREET));
         temp_id=String.valueOf(template_id);

goForEdit();


         // confirm
Toast.makeText(this,
        "Name :"+name+"  id : " +template_id , Toast.LENGTH_LONG)
        .show();
    }
    public void goForEdit(){
        Intent launchSMSTempEdit = new Intent(
                ManageSMSTemplate.this,
                            EmailSMSTempEdit.class);

    //  Intent i = new Intent(ManageSMSTemplate.this, SMSTempEdit.class);
        //i.putExtra("KeyId", temp_id.toString());
         //  startActivity(i);

         //  launchSMSTempEdit.putExtra("selection", temp_id.toString());
       //     Log.d("*** OUTBOUND INTENT: ", "" + launchSMSTempEdit.getExtras().get("selection"));
    //        startActivity(launchSMSTempEdit);

                //  Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
//                  startActivity(launchSMSTempEdit);

                    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
                     //now get Editor
                     SharedPreferences.Editor editor = sharedPref.edit();
                     //put your value
                     editor.putString("userName", temp_id);
                     editor.putString("template_type", "sms");
                     //commits your edits
                     editor.commit();   

                     startActivity(launchSMSTempEdit);

    }


}


EmailSMSTempEdit.java

      /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_template);

       // sms_key_id=getIntent().getStringExtra("id");
 //       String sms_key_id;    
  //      if (savedInstanceState == null) {
   //         Bundle extras = getIntent().getExtras();
     //       if(extras == null) {
       //       sms_key_id= null;
         //   } else {
      //        sms_key_id= extras.getString("STRING_I_NEED");
        //    }
      //  } else {
        //  sms_key_id= (String) savedInstanceState.getSerializable("STRING_I_NEED");
      //  }
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        sms_key_id = sharedPref.getString("userName", "Not Available");
        mTemplateType=sharedPref.getString("template_type", "Not Available");
        Toast.makeText(this, mTemplateType, Toast.LENGTH_LONG).show();
        dba = new MyDB(this);
        dba.open() ;

        //array to hold values to show in spinner 
        nameTypeArr = new String[]{getString(R.string.insert_name_prompt), 
                                   getString(R.string.first_name), 
                                   getString(R.string.last_name)};

        //get views from xml
        mNameBox = (EditText) findViewById(R.id.template_name_box);        
        mSubjectBox = (EditText) findViewById(R.id.template_subject_box);        
        mMessageBox = (EditText) findViewById(R.id.template_message_box);        
        mInsertNameSpinner = (Spinner) findViewById(R.id.insert_name_here_spinner);

        //create adapter for the spinner and set it
        ArrayAdapter<String> mAdapter1= 
            new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, nameTypeArr);

        mAdapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        mInsertNameSpinner.setAdapter(mAdapter1);

        //listener for the spinner
        mInsertNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
        {

            @Override
            public void onItemSelected(AdapterView<?> parent,
                                        View view, int pos, long id) { 

                //if the spinner has just been created, ignore this call to onItemSelected
                if(spinnerBeingCreated == true){
                    spinnerBeingCreated = false;
                    return;
                }
                //what item did the user click in spinner
                String typeOfName = parent.getItemAtPosition(pos).toString();

                //based on user choice, insert corresponding placeholder in text
                if(typeOfName.equals( getString(R.string.first_name) )){
                    insertAtCurrentLocation( getString(R.string.first_name_placeholder) );
                }else if(typeOfName.equals( getString(R.string.last_name) )){
                    insertAtCurrentLocation( getString(R.string.last_name_placeholder) );
                }
                //reset the spinner item selection back to first one
                mInsertNameSpinner.setSelection(0);

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {}
        });


        //if its a template for sms, hide the subject line
        LinearLayout subjectarea = (LinearLayout) findViewById(R.id.template_subject_box_container);

        if(mTemplateType.equals("sms")){
            subjectarea.setVisibility(View.GONE);
        } else if(mTemplateType.equals("email")){
            subjectarea.setVisibility(View.VISIBLE);
        }

        fillData(sms_key_id);

        //Save the template
        //setup Save Template Listener       
        Button saveTemplateButton = (Button) findViewById(R.id.save_template_button);
        saveTemplateButton.setOnClickListener(new OnClickListener(){
            public void onClick(View view){
       //       saveTemplate();

        updateTemplate(sms_key_id);
            }
        });

        //Cancel
        //Cancel Listener       
        Button cancelTemplateButton = (Button) findViewById(R.id.cancel_template_button);
        cancelTemplateButton.setOnClickListener(new OnClickListener(){
            public void onClick(View view){
                finish();
            }
        });
    }

public void fillData(String sms_key_id) {
    Toast.makeText(EmailSMSTempEdit.this, sms_key_id, Toast.LENGTH_LONG).show();


    dba.open();
        String queryStr = 
               "Select " +
                     "*" + " from " +  
                Constants.TABLE_NAME_GREETINGS + 
                " where "+  Constants.KEY_ID_GREET+"=" + sms_key_id ;


        //Toast.makeText(this, queryStr, Toast.LENGTH_SHORT).show();   

           c = dba.getResults(queryStr);
            startManagingCursor(c);

            if(c.moveToFirst()){
                do{

                    mNameBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
                    mMessageBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));

            //      System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_GREET)));
        //          System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
            //      System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));
            //      System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_SETUP_GREET)));
                } while(c.moveToNext());
                }
            }

    public void updateTemplate(String sms_key_id){

        String subject = mSubjectBox.getText().toString();
        String name = mNameBox.getText().toString();
        String message = mMessageBox.getText().toString();
dba.open();     
        //if name is null or empty, don't save
        if(name == null || name.equals("")){
            Toast.makeText(this, R.string.empty_template_name_error, Toast.LENGTH_LONG).show();
            return;
        }

        //whether its sms or email, requied fro db query
        int messageTypeCode = -1;   //for sms, it is 0. For email it is 1

        if(mTemplateType.equals("email")){
            message = subject + subjectMessageDelimiter + message;  //|~| is the delimiter
            messageTypeCode = Constants.EMAIL_CODE;
        } else if(mTemplateType.equals("sms")){
            messageTypeCode = Constants.SMS_CODE;
        }

    String  Stmt = "update  " + 
                Constants.TABLE_NAME_GREETINGS +
                " set "+
                Constants.GREETING_NAME+"='"+name + "',"+
                Constants.GREETING_MESSAGE+"='"+message + "'," +
                Constants.KEY_ID_SETUP_GREET+"='"+messageTypeCode +"'" +
                " where "+ Constants.KEY_ID_GREET+"=" + sms_key_id ;




    dba.execute(Stmt);

    dba.close();
    Toast.makeText(this, "Successfully updated Template: " + name, Toast.LENGTH_LONG).show();   
    //finish the activity
//  setResult(RESULT_OK, null);
    finish();



    }

    @Override
    protected void onDestroy(){
        //dba.close();
        super.onDestroy();
    }

    //insert at currnet cursor location in subject or message field
    private void insertAtCurrentLocation(String str){

        int start, end;

        if(mMessageBox.hasFocus()){
            start = mMessageBox.getSelectionStart();
            end = mMessageBox.getSelectionEnd();
            mMessageBox.getText().replace(Math.min(start, end), Math.max(start, end),
                                            str, 0, str.length());
        } else if(mSubjectBox.hasFocus()){
            start = mSubjectBox.getSelectionStart();
            end = mSubjectBox.getSelectionEnd();
            mSubjectBox.getText().replace(Math.min(start, end), Math.max(start, end),
                                            str, 0, str.length());
        }

    }

    private boolean alreadyExists(String templateName){

        int type_code = -1;

        if(mTemplateType.equals("sms")){
            type_code = Constants.SMS_CODE;
        } else if(mTemplateType.equals("email")){
            type_code = Constants.EMAIL_CODE;
        }

        String query = "Select * from " + Constants.TABLE_NAME_GREETINGS 
                + " where " + Constants.GREETING_NAME + " = '" + templateName 
                + "' AND " +  Constants.KEY_ID_SETUP_GREET + "=" + type_code;

        Cursor c = null;
        Boolean exists = false;

        dba.open();

        try {
            c = dba.getResults( query );
            if (c != null) {
                if (c.moveToFirst()) {
                    exists = (c.getCount() > 0);

                } else {
                    exists = false;
                }
            }
        } catch (Exception e) {
            Log.e("CreateNewTemplate", "Error while checking if name already exists. Details: "+e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (c != null)
                c.close();
            dba.close();
        }
        return exists;
    }

}

1 个答案:

答案 0 :(得分:0)

将光标移动到您单击的列表视图项的位置,然后使用该光标从db获取数据。下面是一个小片段:

yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if(cursor!=null){
                cursor.moveToPosition(position);
                //do your stuff here....
                cursor.close();


            }
        }
    });