无法恢复以前的活动

时间:2016-11-21 04:23:32

标签: java android nullpointerexception back-stack

我需要帮助。我试图回到之前的活动,但当我点击箭头按钮(操作栏)时,它显示错误。有人可以帮帮我..

感谢之前的答案

这是我的代码: 首先,我在KitabActivity中获取数据(所以这是第一个活动): KitabActivity:

public class KitabActivity extends AppCompatActivity {

private List<Kitab> kitabList;
private RecyclerView recyclerView;
private KitabAdapter kitabAdapter;
private RecyclerView.LayoutManager layoutManager;
private Toolbar toolbar;
private ActionBar actionBar;

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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Kitab Hadits");
    setSupportActionBar(toolbar);
    actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    recyclerView = (RecyclerView) findViewById(R.id.rv_main_kitab);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    kitabList = new ArrayList<>();

    getDataKitab();
}

private void getDataKitab() {
    final ProgressDialog loading = ProgressDialog.show(this,"Mohon Tunggu...","Sedang mengambil data...",false,false);
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigKitab.DATA_URL_KITAB, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray jsonArray) {
            loading.dismiss();
            parseData(jsonArray);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            loading.dismiss();
            Toast.makeText(KitabActivity.this, "Gagal koneksi ke server!", Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}

private void parseData(JSONArray jsonArray) {
    for(int i=0;i<jsonArray.length();i++){
        Kitab kitab = new Kitab();
        JSONObject jsonObject = null;
        try{
            jsonObject = jsonArray.getJSONObject(i);
            kitab.setId_kitab(jsonObject.getString(ConfigKitab.TAG_ID_KITAB));
            kitab.setNama_kitab(jsonObject.getString(ConfigKitab.TAG_NAMA_KITAB));
        }catch(JSONException e){
            e.printStackTrace();
        }
        kitabList.add(kitab);
    }
    kitabAdapter = new KitabAdapter(kitabList,this);
    recyclerView.setAdapter(kitabAdapter);
}
}

在KitabAdapter中,我将KEY_ID传递给BabKitabActivity: 这是KitabAdapter:

public class KitabAdapter extends RecyclerView.Adapter<KitabVH> {
private Context context;
List<Kitab> kitabList;

public KitabAdapter(List<Kitab> kitabList, Context context){
    super();
    this.kitabList = kitabList;
    this.context = context;
}
@Override
public KitabVH onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_kitab,parent,false);
    return new KitabVH(view);
}

@Override
public void onBindViewHolder(KitabVH holder, int position) {
    final Kitab kitab = kitabList.get(position);
    holder.bind(kitab);
    holder.cv_kitab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), BabKitabActivity.class);
            intent.putExtra("KEY_ID",kitab.getId_kitab());
            intent.putExtra("KEY_NAMA",kitab.getNama_kitab());
            v.getContext().startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return kitabList.size();
}
}

BabKitabActivity:

public class BabKitabActivity extends AppCompatActivity {

private List<BabKitab> babKitabList;
private RecyclerView recyclerView;
private BabKitabAdapter babKitabAdapter;
private RecyclerView.LayoutManager layoutManager;
private Toolbar toolbarBab;
private ActionBar actionBar;
private String id_kitab;

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

    toolbarBab = (Toolbar) findViewById(R.id.toolbarBab);
    toolbarBab.setTitle(getIntent().getExtras().getString("KEY_NAMA"));
    setSupportActionBar(toolbarBab);
    actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    recyclerView = (RecyclerView) findViewById(R.id.rv_main_bab);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    babKitabList = new ArrayList<>();
    getDataBab();

}

private void getDataBab() {
    id_kitab = getIntent().getExtras().getString("KEY_ID");
    String url = ConfigBabKitab.DATA_URL_BAB+id_kitab;
    final ProgressDialog loading = ProgressDialog.show(this,"Mohon Tunggu...","Sedang mengambil data...",false,false);
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray jsonArray) {
            loading.dismiss();
            parseData(jsonArray);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            loading.dismiss();
            Toast.makeText(BabKitabActivity.this, "Gagal Koneksi ke Server!", Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}

private void parseData(JSONArray response) {
    for(int i=0;i<response.length();i++){
        BabKitab babKitab = new BabKitab();
        JSONObject obj = null;
        try{
            obj = response.getJSONObject(i);
            babKitab.setId_bab_kitab(obj.getString(ConfigBabKitab.TAG_ID_BAB));
            babKitab.setNomor_bab(obj.getString(ConfigBabKitab.TAG_NOMOR_BAB));
            babKitab.setNama_bab(obj.getString(ConfigBabKitab.TAG_NAMA_BAB));
            babKitab.setPenjelasan(obj.getString(ConfigBabKitab.TAG_PENJELASAN));
        }catch(JSONException e){
            e.printStackTrace();
        }

        babKitabList.add(babKitab);
    }
    babKitabAdapter = new BabKitabAdapter(babKitabList,this);
    recyclerView.setAdapter(babKitabAdapter);
}
}

DetailActivity:

public class DetailActivity extends AppCompatActivity {

private RecyclerView recyclerView;
private List<DetailHadits> detailHaditsList;
private DetailAdapter detailAdapter;
private String id_bab_kitab;
private TextView tv_penjelasan;
private String penjelasan;
private CardView cv;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarDetail);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    cv = (CardView) findViewById(R.id.cv);
    tv_penjelasan = (TextView) findViewById(R.id.tv_penjelasan);
    //cv.setVisibility(View.GONE);
    //tv_penjelasan.setVisibility(View.GONE);
    penjelasan = getIntent().getExtras().getString("KEY_PENJELASAN");

    tv_penjelasan.setText(penjelasan);


    recyclerView = (RecyclerView) findViewById(R.id.rv_main_detail);
    //recyclerView.setHasFixedSize(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    detailHaditsList = new ArrayList<>();

    getAyat();

}

private void getAyat() {
    id_bab_kitab = getIntent().getExtras().getString("KEY_ID");
    String url = ConfigDetail.DATA_URL_AYAT+id_bab_kitab;
    final ProgressDialog loading = ProgressDialog.show(this,"Mohon Tunggu...","Sedang mengambil data...",false,false);
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray jsonArray) {
            loading.dismiss();
            parseData(jsonArray);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            loading.dismiss();
            Toast.makeText(DetailActivity.this, "Error", Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}

private void parseData(JSONArray jsonArray) {
    for(int i=0;i<jsonArray.length();i++){
        DetailHadits detailHadits = new DetailHadits();
        JSONObject obj = null;
        try{
            obj = jsonArray.getJSONObject(i);
            detailHadits.setUrlGambarAyat(obj.getString(ConfigDetail.TAG_GAMBAR));
            detailHadits.setTerjemahanAyat(obj.getString(ConfigDetail.TAG_TERJEMAHAN));
        }catch(JSONException e){
            e.printStackTrace();
        }
        detailHaditsList.add(detailHadits);
    }
    detailAdapter = new DetailAdapter(detailHaditsList,this);
    recyclerView.setAdapter(detailAdapter);
}
}

这是日志猫:

FATAL EXCEPTION: main
                                                                             Process: id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits, PID: 15228
                                                                                                      java.lang.RuntimeException: Unable to start activity ComponentInfo{id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits/id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
                                                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
                                                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
                                                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                                          at android.os.Looper.loop(Looper.java:135)
                                                                                                          at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
                                                                                                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                                          at id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity.onCreate(BabKitabActivity.java:46)
                                                                                                          at android.app.Activity.performCreate(Activity.java:5933)
                                                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                                                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
                                                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
                                                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:144) 
                                                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
                                                                                                          at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                                          at android.os.Looper.loop(Looper.java:135) 
                                                                                                          at android.app.ActivityThread.main(ActivityThread.java:5221) 
                                                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                                                          at java.lang.reflect.Method.invoke(Method.java:372) 

提前谢谢;)

所以,在我的情况下,如果KitabActivity有一个KEY_ID(我猜),BabKitabActivity可以加载数据。 我想要的只是回到之前的活动(在这种情况下是BabKitabActivity)而不再获得KEY_ID。

它可以在模拟器或智能手机中使用按钮,但它不能与动作栏中的箭头按钮一起使用,我该怎么办?

3 个答案:

答案 0 :(得分:0)

  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
  at id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity.onCreate(BabKitabActivity.java:46)
penjelasan = getIntent().getExtras().getString("KEY_PENJELASAN");

您可以从getIntent().getExtras()获取Bundle的数据,但是获得了null,因此您获得了NullPointerException,这会导致您的应用崩溃。

答案 1 :(得分:0)

在getIntent()之前的

.getExtras()检查它的null是否

Bundle extras = getIntent().getExtras();
if (extras != null) {
 penjelasan = extras.getString("KEY_PENJELASAN");
}

类似

if (extras != null) {
id_bab_kitab = extras.getString("KEY_ID");
}

答案 2 :(得分:0)

  

无法启动活动ComponentInfo {id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits / id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity}:   java.lang.NullPointerException:尝试调用虚方法   &#39; java.lang.String android.os.Bundle.getString(java.lang.String)&#39;在...上   null对象引用

问题出在您的BatkitabActivity。您从string获取的intent为空。在获取字符串值之前,您可以检查intent是否为null。

Bundle extras = getIntent().getExtras();
if (extras != null) {
  ....
}