안드로이드 다른 클래스의 String 내용을 또 다른 클래스에 가져오려는데 java.lang.NullPointerException이 뜹니다..


해결법좀 알려주세요 ㅠㅠ

ListViewActivity.java

public class ListViewActivity extends Activity implements SearchView.OnQueryTextListener,SearchView.OnCloseListener{

    private EditText editUserName;
    private EditText editUserTel;
    public TextView tvUserName;
    public TextView tvUserTel;
    private DBAdapter customAdapter;
    private DatabaseHelper databaseHelper;
    private static final int ENTER_DATA_REQUEST_CODE = 1;
    private ListView listView;
    //이부분의 내용을 다른클래스에 가져오려고합니다.
    public String latestUserName;
    public String latestUserTel;
    //
    public String selectedUserName;
    public String selectedUserTel;
    public SearchView searchUser;

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_list);

        searchUser = (SearchView)findViewById(R.id.search_User);
        searchUser.setQueryHint("이름 검색");
        searchUser.setIconifiedByDefault(false);
        searchUser.setOnQueryTextListener(this);
        searchUser.setOnCloseListener(this);

        databaseHelper = new DatabaseHelper(this);

        tvUserName = (TextView)findViewById(R.id.tv_user_name);
        tvUserTel = (TextView)findViewById(R.id.tv_user_tel);

        Cursor cursor = (Cursor) databaseHelper.getAllData();

        if(cursor!=null && cursor.getCount()!=0){
            cursor.moveToLast();
            **latestUserName** = cursor.getString(cursor.getColumnIndexOrThrow(databaseHelper.USER_TABLE_COLUMN_NAME));
            **latestUserTel** = cursor.getString(cursor.getColumnIndexOrThrow(databaseHelper.USER_TABLE_COLUMN_TEL));

        }else{
            Toast.makeText(ListViewActivity.this, "데이터가 존재하지 않음", Toast.LENGTH_SHORT).show();
        }

        Log.d(TAG, "latestUserINfo : " + latestUserName + " " + latestUserTel);

        listView = (ListView) findViewById(R.id.list_data);
        listView.setOnItemClickListener(new OnItemClickListener() {

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

                Toast.makeText(ListViewActivity.this, "Clicked Item id : "+id, Toast.LENGTH_SHORT).show();
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, final long id) {

                Cursor cursor = (Cursor) parent.getItemAtPosition(position);

                selectedUserName = cursor.getString(cursor.getColumnIndexOrThrow(databaseHelper.USER_TABLE_COLUMN_NAME));
                selectedUserTel = cursor.getString(cursor.getColumnIndexOrThrow(databaseHelper.USER_TABLE_COLUMN_TEL));

                final int item_id = cursor.getInt(cursor.getColumnIndex(databaseHelper.USER_TABLE_COLUMN_ID));

                PopupMenu popup = new PopupMenu(ListViewActivity.this, view);
                getMenuInflater().inflate(R.menu.menu_listview,popup.getMenu());

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.modify:

                                LayoutInflater inflater =LayoutInflater.from(ListViewActivity.this);
                                View layout = inflater.inflate(R.layout.activity_edit_user,null);

                                editUserName = (EditText)layout.findViewById(R.id.edit_user_name);
                                editUserTel = (EditText)layout.findViewById(R.id.edit_user_tel);

                                AlertDialog.Builder editAlert = new AlertDialog.Builder(ListViewActivity.this);
                                editAlert.setTitle("EditUser");
                                editAlert.setView(layout);


                                editAlert.setPositiveButton("Modify", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        String userName = editUserName.getText().toString();
                                        String userTel = editUserTel.getText().toString();
                                        databaseHelper.updateUser(item_id,userName,userTel);

                                        databaseHelper.getAllData();

                                        customAdapter = new DBAdapter(ListViewActivity.this, databaseHelper.getAllData());
                                        listView.setAdapter(customAdapter);
                                    }
                                });
                                editAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                });
                                AlertDialog ad = editAlert.create();
                                ad.show();
                                break;
                            case R.id.delete:

                                AlertDialog.Builder deleteAlert = new AlertDialog.Builder(ListViewActivity.this);
                                deleteAlert.setMessage("해당 유저가 삭제됩니다.\n삭제하시겠습니까??\nUser name : "+selectedUserName).setCancelable(false).setNegativeButton("Confirm", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        databaseHelper.delete(selectedUserName);
                                        databaseHelper.getAllData();

                                        customAdapter = new DBAdapter(ListViewActivity.this, databaseHelper.getAllData());
                                        listView.setAdapter(customAdapter);
                                    }
                                }).setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                });
                                AlertDialog alert = deleteAlert.create();
                                alert.show();
                                break;
                        }
                        return false;
                    }
                });
                popup.show();
                return false;
            }
        });

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                customAdapter = new DBAdapter(ListViewActivity.this, databaseHelper.getAllData());
                listView.setAdapter(customAdapter);
            }
        });
    }

    public void onClickEnterData(View btnAdd) {

        startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);

    }

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

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {

            databaseHelper.insertData(data.getExtras().getString("tag_user_name"), data.getExtras().getString("tag_user_pin"));

            customAdapter.changeCursor(databaseHelper.getAllData());
        }
    }
    @Override
    public boolean onClose() {
        showResults("");
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        if(query.length()==0){
            customAdapter = new DBAdapter(ListViewActivity.this, databaseHelper.getAllData());
            listView.setAdapter(customAdapter);
        }else {
            showResults(query);
        }
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        if(newText.length()==0){
            customAdapter = new DBAdapter(ListViewActivity.this, databaseHelper.getAllData());
            listView.setAdapter(customAdapter);
        }else{
            showResults(newText);
        }
        return false;
    }

    public void showResults(String query){

        Cursor cursor = databaseHelper.searchUser((query != null ? query.toString() : "@@@@"));

        if(cursor == null){
        }else{

            String[] from = new String[]{
                    DatabaseHelper.USER_TABLE_COLUMN_NAME,
                    DatabaseHelper.USER_TABLE_COLUMN_TEL
            };

            int[] to = new int[]{
                    R.id.tv_user_name, R.id.tv_user_tel
            };

            SimpleCursorAdapter adapter = new SimpleCursorAdapter(ListViewActivity.this, R.layout.activity_userlist_item, cursor, from, to);
            listView.setAdapter(adapter);
        }
    }

}

firstViewActivity.java

package com.example.cracking.groupproj;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

public class firstViewActivity extends Activity{

    String latestUserName;
    String latestUserTel;
    ListView recentList;
    DBAdapter listAdapter;
    ListViewActivity listViewActivity;

    protected void onCreate(Bundle savedInstanceState){

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

        recentList = (ListView)findViewById(R.id.recentListView);

        //여기서 NullPointerException에러가 뜹니다.
        latestUserName = listViewActivity.latestUserName.toString();
        latestUserTel = listViewActivity.latestUserTel.toString();
        //

        long now = System.currentTimeMillis();

        Date date = new Date(now);

        SimpleDateFormat CurDateFormat = new SimpleDateFormat("yyyy년 MM월 dd일");

        String strCurDate = CurDateFormat.format(date);

        TextView recentDate = (TextView)findViewById(R.id.recentDate);
        recentDate.setText("최근 추가 날짜 : "+strCurDate);

    }

}
  • 2016년 06월 05일에 수정됨
    리눅스(유닉스) 기반의 시스템에서 웹 서비스를 개발하고 있습니다.
  • 2016년 06월 05일에 작성됨

조회수 309


1 답변


Activity간의 데이터 의존성은 설정하지 않는 것이 좋습니다.

Acitvity간에 데이터 전송은 Intent를 사용해서 합니다. 링크를 참고해보세요.

혹은 SharedPreference를 사용해서, 액티비티간의 값을 공유하세요. 링크2

  • 2016년 06월 05일에 작성됨
    리눅스(유닉스) 기반의 시스템에서 웹 서비스를 개발하고 있습니다.

로그인이 필요한 기능입니다.

Hashcode는 개발자들을 위한 무료 QnA사이트 입니다. 작성한 답변에 다른 개발자들이 댓글을 작성하거나 좋아요/싫어요를 할 수 있기 때문에 계정을 필요로 합니다.
► 로그인
► 계정만들기
Close