마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

ListActivity를 변경하여 Activity에서 ListView 사용하는 방법

0 추천

http://www.androidside.com/bbs/board.php?bo_table=B56&wr_id=24614

내용입니다.

package com.example.note;

import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class NoteList extends ListActivity {
	
	private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;
	
    private static final int DELETE_ID = Menu.FIRST;
	private int mNoteNumber = 1;
	
	private NotesDbAdapter mDbHelper;
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notelist);
		mDbHelper = new NotesDbAdapter (this);
		mDbHelper.open();
		fillData();


		registerForContextMenu(getListView());
		Button addnote = (Button)findViewById(R.id.addnotebutton);

		addnote.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				createNote();
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.notelist_menu, menu);
		return true;		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.menu_about:
	          
	           AlertDialog.Builder dialog = new AlertDialog.Builder(NoteList.this);
	           dialog.setTitle("About");
	           dialog.setMessage("Hello! I'm Heng, the creator of this application. This application is created based on learning." +
	           		" Used it on trading or any others activity that is related to business is strictly forbidden."
	        		   +"If there is any bug is found please freely e-mail me. "+
	           			"\n\tedisonthk@gmail.com"
	        		   );
	           dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
	        	   @Override
	        	   public void onClick(DialogInterface dialog, int which) {
	        		   dialog.cancel();
					
	        	   }
	           });
	           dialog.show();	           
	           return true;
	        
	        default:
	            return super.onOptionsItemSelected(item);
	        }
	    }
	
	private void createNote() {
		Intent i = new Intent(this, NoteEdit.class);
        startActivityForResult(i, ACTIVITY_CREATE);    	
    }
	
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, NoteEdit.class);
        i.putExtra(NotesDbAdapter.KEY_ROWID, id);
        startActivityForResult(i, ACTIVITY_EDIT);
    }

	private void fillData() {
        // Get all of the notes from the database and create the item list
        Cursor notesCursor = mDbHelper.fetchAllNotes();
        startManagingCursor(notesCursor);
        

        String[] from = new String[] { NotesDbAdapter.KEY_TITLE ,NotesDbAdapter.KEY_DATE};
        int[] to = new int[] { R.id.text1 ,R.id.date_row};
        
        // Now create an array adapter and set it to display using our row
        SimpleCursorAdapter notes =
            new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
        setListAdapter(notes);
    }
	
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, R.string.menu_delete);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case DELETE_ID:
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteNote(info.id);
                fillData();
                return true;
        }
        return super.onContextItemSelected(item);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();        
    }   
    
}

리스트액티비티 예제를 가져와서 Activity 의 Listview 로 수정하려합니다.

// registerForContextMenu(getListView());

이걸 없애고,

 public class NoteActivity extends Activity {

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

        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);

이런식으로 수정하면 되는거 아닌가요?

 몰라서 여쭤봅니다....
하람군 (350 포인트) 님이 2017년 3월 24일 질문
글자수 초과로 오류메시지는 여기 남깁니다.

 Process: com.example.note, PID: 17059
                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.note/com.example.note.NoteActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
                                                                      at android.app.ActivityThread.access$1100(ActivityThread.java:221)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:158)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:7225)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                      at com.example.note.NoteActivity.fillData(NoteActivity.java:125)
                                                                      at com.example.note.NoteActivity.onCreate(NoteActivity.java:45)
                                                                      at android.app.Activity.performCreate(Activity.java:6876)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349) 
                                                                      at android.app.ActivityThread.access$1100(ActivityThread.java:221) 
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                      at android.os.Looper.loop(Looper.java:158) 
                                                                      at android.app.ActivityThread.main(ActivityThread.java:7225) 
                                                                      at java.lang.reflect.Method.invoke(Native Method) 
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

1개의 답변

0 추천
NoteActivity 내에서 onCreate 오버라이딩 메서드에 setContentView가 있는지 확인하세요..

근데 ListActivity로부터 상속받던걸 Activity로 상속하시네요...???
멍게 님이 2017년 3월 24일 답변
아..우선  activity 변경해볼게요
set content view는 잘있습니다
...