Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/203.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 单击所选按钮后,applicaton已停止显示logcat错误_Java_Android - Fatal编程技术网

Java 单击所选按钮后,applicaton已停止显示logcat错误

Java 单击所选按钮后,applicaton已停止显示logcat错误,java,android,Java,Android,在我的应用程序中,我将动态提供复选框,并在我提供的“获取选定项”按钮上方提供复选框,如果您单击该按钮,它将获取我们在列表视图中提供的已检查数据。但现在,单击“按钮选择”后,应用程序已停止 Mainactivity.java public class MainActivity extends Activity implements FetchDataListener,OnClickListener { private static final int ACTIVITY_CREATE=0;

在我的应用程序中,我将动态提供复选框,并在我提供的“获取选定项”按钮上方提供复选框,如果您单击该按钮,它将获取我们在列表视图中提供的已检查数据。但现在,单击“按钮选择”后,应用程序已停止

Mainactivity.java

public class MainActivity extends Activity implements FetchDataListener,OnClickListener
{
    private static final int ACTIVITY_CREATE=0;
    private ProgressDialog dialog;
    ListView lv;
    private List<Application> items;
    private Button btnGetSelected;
    //private ProjectsDbAdapter mDbHelper;
    //private SimpleCursorAdapter dataAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_list_item);  
         //mDbHelper = new ProjectsDbAdapter(this);
            //mDbHelper.open();
            //fillData();
            //registerForContextMenu(getListView());

     lv =(ListView)findViewById(R.id.list);
     btnGetSelected = (Button) findViewById(R.id.btnget);
        btnGetSelected.setOnClickListener(this);

        initView();
    }



    private void initView()
    {
        // show progress dialog
        dialog = ProgressDialog.show(this, "", "Loading...");
        String url = "http://dry-brushlands-3645.herokuapp.com/posts.json";
        FetchDataTask task = new FetchDataTask(this);
        task.execute(url);

        //mDbHelper.open();     
        //Cursor projectsCursor = mDbHelper.fetchAllProjects();
        //startManagingCursor(projectsCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        //String[] from = new String[]{ProjectsDbAdapter.KEY_TITLE};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        //int[] to = new int[]{R.id.text1};

        /* Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter projects = 
                new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to);
        setListAdapter(projects);
        */
        // create the adapter using the cursor pointing to the desired data 
        //as well as the layout information
         /*dataAdapter  = new SimpleCursorAdapter(
          this, R.layout.activity_row, 
          projectsCursor, 
          from, 
          to,
          0);
         setListAdapter(dataAdapter);
        */
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.activity_main, menu);
        super.onCreateOptionsMenu(menu);
         MenuInflater mi = getMenuInflater();
            mi.inflate(R.menu.activity_main, menu); 
        return true;

    }

     @Override
        public boolean onMenuItemSelected(int featureId, MenuItem item) {

                createProject();

            return super.onMenuItemSelected(featureId, item);
     }

     private void createProject() {
            Intent i = new Intent(this, ProjectEditActivity.class);
            startActivityForResult(i, ACTIVITY_CREATE);   
        }

     @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
            super.onActivityResult(requestCode, resultCode, intent);
            initView();
        }

    @Override
    public void onFetchComplete(List<Application> data)
    {
        // dismiss the progress dialog
        if ( dialog != null )
            dialog.dismiss();
        // create new adapter
        ApplicationAdapter adapter = new ApplicationAdapter(this, data);
        // set the adapter to list
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {

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

                CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
                Application bean = items.get(position);
                if (bean.isSelected()) {
                    bean.setSelected(false);
                    chk.setChecked(false);
                } else {
                    bean.setSelected(true);
                    chk.setChecked(true);
                }

            }
        });
    }

    // Toast is here...
        private void showToast(String msg) {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }

    @Override
    public void onFetchFailure(String msg)
    {
        // dismiss the progress dialog
        if ( dialog != null )
            dialog.dismiss();
        // show failure message
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }



    @Override
    public void onClick(View v) {
        StringBuffer sb = new StringBuffer();

        // Retrive Data from list
        for (Application bean : items) {

            if (bean.isSelected()) {
                sb.append(bean.getContent());
                sb.append(",");
            }
        }

        showAlertView(sb.toString().trim());

    }

    private void showAlertView(String str) {
        AlertDialog alert = new AlertDialog.Builder(this).create();
        if (TextUtils.isEmpty(str)) {
            alert.setTitle("Not Selected");
            alert.setMessage("No One is Seleceted!!!");
        } else {
            // Remove , end of the name
            String strContactList = str.substring(0, str.length() - 1);

            alert.setTitle("Selected");
            alert.setMessage(strContactList);
        }
        alert.setButton("Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        alert.show();
    }


    @Override
    public void onBackPressed() {
        AlertDialog alert_back = new AlertDialog.Builder(this).create();
        alert_back.setTitle("Quit?");
        alert_back.setMessage("Are you sure want to Quit?");

        alert_back.setButton("No", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alert_back.setButton2("Yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                MainActivity.this.finish();
            }
        });
        alert_back.show();
    }



    @Override
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        // TODO Auto-generated method stub

    }
单击所选的BTN后,应用程序已停止

这是我的Application.java

public class Application {
    private String content;
    private boolean selected;


    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

}
在我的代码中,我使用asynctask获取数据,在这里我还附加了该代码

public class FetchDataTask extends AsyncTask<String, Void, String>
{
    private final FetchDataListener listener;
    private String msg;

    public FetchDataTask(FetchDataListener listener)
    {
        this.listener = listener;
    }

    @Override
    protected String doInBackground(String... params)
    {
        if ( params == null )
            return null;
        // get url from params
        String url = params[0];
        try
        {
            // create http connection
            HttpClient client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            // connect
            HttpResponse response = client.execute(httpget);
            // get response
            HttpEntity entity = response.getEntity();
            if ( entity == null )
            {
                msg = "No response from server";
                return null;
            }
            // get response content and convert it to json string
            InputStream is = entity.getContent();
            return streamToString(is);
        }
        catch ( IOException e )
        {
            msg = "No Network Connection";
        }
        return null;
    }

    @Override
    protected void onPostExecute(String sJson)
    {
        if ( sJson == null )
        {
            if ( listener != null )
                listener.onFetchFailure(msg);
            return;
        }
        try
        {
            // convert json string to json object
            JSONObject jsonObject = new JSONObject(sJson);
            JSONArray aJson = jsonObject.getJSONArray("post");
            // create apps list
            List<Application> apps = new ArrayList<Application>();
            for ( int i = 0; i < aJson.length(); i++ )
            {
                JSONObject json = aJson.getJSONObject(i);
                Application app = new Application();
                app.setContent(json.getString("content"));
                // add the app to apps list
                apps.add(app);
            }
            //notify the activity that fetch data has been complete
            if ( listener != null )
                listener.onFetchComplete(apps);
        }
        catch ( JSONException e )
        {
            e.printStackTrace();
            msg = "Invalid response";
            if ( listener != null )
                listener.onFetchFailure(msg);
            return;
        }
    }

    /**
     * This function will convert response stream into json string
     * 
     * @param is
     *            respons string
     * @return json string
     * @throws IOException
     */
    public String streamToString(final InputStream is) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try
        {
            while ( (line = reader.readLine()) != null )
            {
                sb.append(line + "\n");
            }
        }
        catch ( IOException e )
        {
            throw e;
        }
        finally
        {
            try
            {
                is.close();
            }
            catch ( IOException e )
            {
                throw e;
            }
        }
        return sb.toString();
    }
}
公共类FetchDataTask扩展了AsyncTask
{
私有最终获取数据侦听器;
私有字符串msg;
公共FetchDataTask(FetchDataListener侦听器)
{
this.listener=listener;
}
@凌驾
受保护的字符串doInBackground(字符串…参数)
{
if(params==null)
返回null;
//从参数获取url
字符串url=params[0];
尝试
{
//创建http连接
HttpClient=new DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(url);
//连接
HttpResponse response=client.execute(httpget);
//得到回应
HttpEntity=response.getEntity();
if(实体==null)
{
msg=“服务器无响应”;
返回null;
}
//获取响应内容并将其转换为json字符串
InputStream=entity.getContent();
返回streamToString(is);
}
捕获(IOE异常)
{
msg=“无网络连接”;
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串sJson)
{
if(sJson==null)
{
if(侦听器!=null)
onFetchFailure(msg);
返回;
}
尝试
{
//将json字符串转换为json对象
JSONObject JSONObject=新的JSONObject(sJson);
JSONArray aJson=jsonObject.getJSONArray(“post”);
//创建应用程序列表
列表应用程序=新建ArrayList();
对于(int i=0;i
06-04 10:07:49.857:E/AndroidRuntime(2454):java.lang.NullPointerException
06-04 10:07:49.857:E/AndroidRuntime(2454):在com.example.jsonandroid.MainActivity.onClick(MainActivity.java:174)


这个错误很明显,您在onClick上有一个nullPointerException,请检查这一行:
applicationbean:items
我认为存在null指针。

onClick内的下一行是问题的根源:

 for (Application bean : items) {

 ...

 } 
此处“项目”未初始化。因此,NullpointerException

您必须在如下位置对其进行初始化:

private ArrayList<Application> items = new ArrayList<Application>();
private ArrayList items=new ArrayList();

然后在列表中有一些数据来执行必要的操作

假设
onFetchComplete
是填充数据的内容,并在之前调用

for (Application bean : items) {
调用时,您需要在那里填充项目。所以

@Override
public void onFetchComplete(List<Application> data) {
    this.items = data;
@覆盖
公共void onFetchComplete(列表数据){
此项=数据;

但是如果看不到所有代码,就很难判断发生了什么。

MainActivity第174行是什么?省去了我们将整个内容复制并粘贴到文本编辑器/idefor(应用程序bean:items)中的麻烦{这是一行显示错误的代码,你能看到我在上面的代码中是这样初始化的吗,比如这个私有列表项;这不是初始化,只是声明。这样做不会为此分配内存。我不能在你的代码中任何地方添加我要求你添加的行。私有列表项=新列表();将解决空指针异常。但是,如果希望执行for循环中的代码,则需要将类型为“application”的数据添加到项目(列表)中。如果我添加的代码无法实例化类型列表,则会显示如下错误,in=new“list”在列表中,它显示了我上面提到的所有代码,你可以看到我的所有代码,告诉Dude你必须初始化项,并且当你指向列表的位置时确保你有数据为什么我们使用该代码,该代码的功能是什么,它是用html标记获取的,但是我提到没有html标记,你可以在我的适配器类别中看到该代码打开一个新问题-应用程序已停止
for (Application bean : items) {
@Override
public void onFetchComplete(List<Application> data) {
    this.items = data;