私のアプリでは、チェックボックスを動的に提供し、選択するための1つのボタンの上に提供します.ボタンをクリックすると、リストビューで指定したチェック済みのデータを取得する必要があります.しかし、ボタン選択をクリックした直後に、アプリケーションは停止。
メインアクティビティ.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
}
これは私のアダプタ クロス、Applicationadapter.java です。
public class ApplicationAdapter extends ArrayAdapter<Application>
{
private List<Application> items;
private LayoutInflater inflator;
public ApplicationAdapter(Context context, List<Application> items)
{
super(context, R.layout.activity_row, items);
this.items = items;
inflator = LayoutInflater.from(getContext());
}
@Override
public int getCount()
{
return items.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
//View v = convertView;
if ( convertView == null )
{
convertView = inflator.inflate(R.layout.activity_row, null);
LayoutInflater li = LayoutInflater.from(getContext());
//convertView = inflator.inflate(R.layout.app_custom_list, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.text1);
holder.chk = (CheckBox) convertView.findViewById(R.id.checkbox);
holder.chk
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton view,
boolean isChecked) {
int getPosition = (Integer) view.getTag();
items.get(getPosition).setSelected(view.isChecked());
}
});
convertView.setTag(holder);
convertView.setTag(R.id.text1, holder.text1);
convertView.setTag(R.id.checkbox, holder.chk);
}else {
holder = (ViewHolder) convertView.getTag();
}
Application app = items.get(position);
holder.chk.setTag(position);
holder.text1.setText(Html.fromHtml(items.get(position).getContent()));
holder.chk.setChecked(items.get(position).isSelected());
if ( app != null )
{
TextView titleText = (TextView) convertView.findViewById(R.id.titleTxt);
if ( titleText != null )
titleText.setText(Html.fromHtml(app.getContent()).toString());
//titleText.setText(app.getContent());
//holder.chk.setChecked(((View) Html.fromHtml(app.getContent())).isSelected());
}
return convertView;
}
static class ViewHolder {
public TextView text1;
public CheckBox chk;
}
//return convertView;
}
ここで、logcat エラーについても言及します。
06-04 10:07:49.857: E/AndroidRuntime(2454): FATAL EXCEPTION: main
06-04 10:07:49.857: E/AndroidRuntime(2454): java.lang.NullPointerException
06-04 10:07:49.857: E/AndroidRuntime(2454): at com.example.jsonandroid.MainActivity.onClick(MainActivity.java:174)
06-04 10:07:49.857: E/AndroidRuntime(2454): at android.view.View.performClick(View.java:4202)
06-04 10:07:49.857: E/AndroidRuntime(2454): at android.view.View$PerformClick.run(View.java:17340)
06-04 10:07:49.857: E/AndroidRuntime(2454): at android.os.Handler.handleCallback(Handler.java:725)
06-04 10:07:49.857: E/AndroidRuntime(2454): at android.os.Handler.dispatchMessage(Handler.java:92)
06-04 10:07:49.857: E/AndroidRuntime(2454): at android.os.Looper.loop(Looper.java:137)
06-04 10:07:49.857: E/AndroidRuntime(2454): at android.app.ActivityThread.main(ActivityThread.java:5039)
06-04 10:07:49.857: E/AndroidRuntime(2454): at java.lang.reflect.Method.invokeNative(Native Method)
06-04 10:07:49.857: E/AndroidRuntime(2454): at java.lang.reflect.Method.invoke(Method.java:511)
06-04 10:07:49.857: E/AndroidRuntime(2454): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-04 10:07:49.857: E/AndroidRuntime(2454): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-04 10:07:49.857: E/AndroidRuntime(2454): at dalvik.system.NativeStart.main(Native Method)
btngetselected をクリックした後、アプリが停止しました
これは私の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();
}
}