2014-06-30 55 views
-7

这是我在StackExchange上的第一篇文章。 我是一名非常初学Android开发人员。我正在制作一个保存数组(列表)的应用程序。但不幸的是,当我运行我的应用程序时,显示{不幸的是,Shop已经停止!}。我对这个错误非常熟悉,并且很多时候我也能够通过它。但这一次,我无法弄清楚我做错了什么。我的代码看起来很完美,但不知何故仍然显示错误。 我在下面粘贴我的java代码。请通过我的代码并指出我的错误! PLEASE〜!不幸的是,[APP]已停止!我究竟做错了什么?

AddItem.java

package com.rcube.shop; 
import java.util.ArrayList; 
import java.util.HashSet; 
import java.util.Set; 
import android.app.Activity; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.preference.PreferenceManager; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 
public class AddItem extends Activity{ 
SharedPreferences store = PreferenceManager.getDefaultSharedPreferences(getApplication()); 
SharedPreferences.Editor edit = store.edit(); 
ArrayList<String> itemarray = new ArrayList<String>(); 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.add_item); 
    Button addnewitem = (Button) findViewById(R.id.addnewitem); 
    final EditText getitemname = (EditText)findViewById(R.id.getitem); 

    addnewitem.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      String newitemname = getitemname.getText().toString(); 
      if(newitemname.length()!=0){ 
       itemarray.add(newitemname); 
       Set<String> itemset = new HashSet<String>(itemarray); 
       edit.putStringSet("items_set", itemset); 
       edit.commit(); 
      }else{ 
       Toast.makeText(AddItem.this, "Write Item name before submitting!", Toast.LENGTH_LONG).show();    
      } 
     } 
    }); 


} 


} 

请告诉我,我做错了。而且我也在Android Manifest中添加了新的android活动,所以这个错误并不是因为这个。 再次感谢! PEACE〜!

+5

后logcat输出。 –

+0

我认为您的SharedPreferences和编辑器分配得太早。 –

+0

将手机置于调试模式。当它崩溃时,它会指向导致问题的线路。确保该应用程序正在进行调试(在“设备”列表中有一个绿色的小bug旁边) – Gentatsu

回答

0

findViewById后把这两行写入onCreate()之内,那么你可以使用上下文。

SharedPreferences store = PreferenceManager.getDefaultSharedPreferences(getApplication()); 
SharedPreferences.Editor edit = store.edit(); 
4

好像你之后setContentView

SharedPreferences store = PreferenceManager.getDefaultSharedPreferences(getApplication()); 
SharedPreferences.Editor edit = store.edit(); 

在此之前,你不会得到情境的getApplicationContect()

onCreate将这个越来越NPE。

希望这会有所帮助。

+0

谢谢男人......!它的工作...真的很感激它!但你能解释我做错了什么吗?以及为什么它一开始没有奏效! – Rish

+0

@ user3789667'setContentView'呈现您的xml,然后您可以获取应用程序上下文。您试图在'setContentView'之前引用应用程序上下文。所以它抛出空指针异常。请参阅更多[这里](http://developer.android.com/reference/android/app/Activity.html#setContentView%28android.view.View%29):) –

+0

@ user3789667标记答案正确,如果问题解决了:)所以它被从无人答复的列表中删除 –