까까
10
2019-07-11 22:58:11
2
173

안드로이드 EditText.getText.tostring 에러 질문입니다.


아래와 같은 에러가 발생되는데 원인을 모르겠습니다..
도와주시면 감사하겠습니다 ㅠㅠ
getText.tostring은 원래 널값을 허용하지 않나요??
저는 널값을 허용하고 싶어서요...
Call<List<DietMenuVO>> call = rs.listDiet(keyword);
이부분에 널값이 들어가면 모든 리스트가 출력되도록 하고 싶거든요..
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.calog, PID: 31255
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calog/com.example.calog.Diet.FoodSearchActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.example.calog.Diet.FoodSearchActivity.onCreate(FoodSearchActivity.java:59)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
package com.example.calog.Diet;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.calog.MainHealthActivity;
import com.example.calog.R;
import com.example.calog.RemoteService;
import com.example.calog.VO.DietMenuVO;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.example.calog.RemoteService.BASE_URL;

public class FoodSearchActivity extends AppCompatActivity {

RecyclerView dietList;
Button btnSave, btnSearch;
ImageView btnBack, btnHome;
EditText searchEdit;
Intent intent;
Retrofit retrofit;
RemoteService rs;
List<DietMenuVO> array;
TabLayout tabLayout;
ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_search);

tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.foodListPager);
dietList = findViewById(R.id.dietList);
searchEdit = findViewById(R.id.searchEdit);
btnSearch = findViewById(R.id.btnSearch);
System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<searchEdit111111:" + searchEdit.getText().toString());
// 페이지 이동소스 메서드로 만드름.
pageTrans();

// 레트로핏빌더 생성 - 통신
rsBuilder();

// 통신 + 어댑터 + VO세팅
// callviewPagerAdapter();

//어댑터 설정 ( 데이터 VO에 넣음)
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);

//tablelayout과 pager연결
tabLayout.setupWithViewPager(viewPager);

// 검색 버튼 클릭시
// btnSearch.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// }
// });

}

@Override
protected void onPostResume() {
super.onPostResume();
}


//검색 페이저
private class PagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
String[] tabTitle = {"검색", "자주 찾는 음식", "내음식"};


//생성자로 데이터를 던져서 바차트를 다르게 표현해야함.
public PagerAdapter(FragmentManager fm) {
super(fm);

//가짜 데이터 집어넣기 실제 구현할때 DB와 연계할것
final List<DietMenuVO> dietMenuArray = new ArrayList<DietMenuVO>();
try {
System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<searchEdit222222:" + searchEdit.getText().toString());
// String keyword = searchEdit.getText().toString();
String keyword = "달걀";
// System.out.println(" <<<<<<<<<<<<<<<<<<<<<< keyword : " + keyword);
//String keyword = "달걀";

Call<List<DietMenuVO>> call = rs.listDiet(keyword);
call.enqueue(new Callback<List<DietMenuVO>>() {
@Override
public void onResponse(Call<List<DietMenuVO>> call, Response<List<DietMenuVO>> response) {
array = response.body();
// System.out.println("<<<<<<<<<<<<<<<<<onResponse" + array.toString());
for (int i = 0; i < array.size(); i++) {
dietMenuArray.add(new DietMenuVO(array.get(i).getDiet_menu_name(), array.get(i).getCalorie()));
i++;
}
}

@Override
public void onFailure(Call<List<DietMenuVO>> call, Throwable t) {
// Log("Main 통신", "에러 "+t.getLocalizedMessage());
}
});
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
}
// dietMenuArray.add(new DietMenuVO("아이템에서 갑슬 가져와야 하나?", 300));
// dietMenuArray.add(new DietMenuVO("짜장면", 300));
// dietMenuArray.add(new DietMenuVO("우동", 200));
// dietMenuArray.add(new DietMenuVO("탕수육", 400));

//자주 찾는 음식
List<DietMenuVO> MyDietList = new ArrayList<DietMenuVO>();

//내 음식
fragments.add(new DietFragment(dietMenuArray, true)); //검색
fragments.add(new DietFragment(dietMenuArray, false)); //자주 찾는 음식
fragments.add(new DietFragment(dietMenuArray, false)); //내 음식
}

@Override
public Fragment getItem(int position) {
return fragments.get(position);
}

@Override
public int getCount() {
return fragments.size();
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {

return tabTitle[position]; //탭레이아웃 타이틀설정
}
}


public void pageTrans() {

btnBack = findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
btnHome = findViewById(R.id.btnHome);
btnHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent = new Intent(FoodSearchActivity.this, MainHealthActivity.class);
startActivity(intent);
}
});
}

private void rsBuilder() {
retrofit = new Retrofit.Builder() //Retrofit 빌더생성
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
rs = retrofit.create(RemoteService.class); //API 인터페이스 생성
}

/*
public void callviewPagerAdapter() {
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);

}
*/



}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".Diet.DietFragment">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
android:id="@+id/searchEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/icon_search"
android:hint="검색어"
android:text=""/>
<!--android:visibility="gone"-->


<Button
android:id="@+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="검색" />
</RelativeLayout>


<androidx.recyclerview.widget.RecyclerView
android:id="@+id/dietList"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:clickable="true"
android:src="@android:drawable/ic_input_add" />
</LinearLayout>



0
0
  • 답변 2

  • CyanGlint
    510
    2019-07-12 09:35:49 작성 2019-07-12 09:36:16 수정됨

    null에 toString()을 호출하는게 가능한 일인지 잠깐 고민해보세요.

    원하시는 형태로 구현하려면 null체크를 거치시거나 String.valueOf() 등을 사용하셔야 할것 같네요.

    0
  • 까까
    10
    2019-07-16 09:43:44

    답변 주셔서 감사합니다.

    인플레이터를 사용하라는 조언이 있어 해봤는데 널값도 가져와지더라구요. 

    0
  • 로그인을 하시면 답변을 등록할 수 있습니다.