2017-02-20 17 views
0

私はlistviewに少し問題があります。ボタンをクリックするとチェックボックスが選択されたlistviewの値を取得したいと思います。今まで私はチェックボックスでリストビューを作成し、mysqlからすべての値をフェッチしましたが、チェックされたリストビューの値を取得できません。listviewチェックボックスから値を取得するには?

これは私がクリックtestbutton(ボタン)でこれを実施している私のクラス

public class ListViewMultipleSelectionActivity extends Activity{ 
    Button button; 
    String myJSON; 

    private static final String TAG_NAME = "cat_name"; 

    JSONArray peoples = null; 

    ArrayList<HashMap<String, String>> personList; 

    ListView list1; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     personList = new ArrayList<HashMap<String,String>>(); 
     list1 = (ListView) findViewById(R.id.list); 
     button = (Button)findViewById(R.id.testbutton); 
     getlat(); 



     button.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 


      } 
     }); 

    } 

    public void getlat(){ 
     class GetDataJSON extends AsyncTask<String, Void, String> { 
      public void onPreExecute() { 
      } 
      @Override 
      protected String doInBackground(String... params) { 

       InputStream inputStream = null; 
       String result = null; 
       try { 

        URL url = new URL("http://xxxxxxxxxxxx/category.php"); 

        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
        conn.setReadTimeout(15000 /* milliseconds */); 
        conn.setConnectTimeout(15000 /* milliseconds */); 
        conn.setRequestMethod("POST"); 
        conn.setDoInput(true); 
        conn.setDoOutput(true); 
        OutputStream os = conn.getOutputStream(); 

        os.close(); 

        int responseCode=conn.getResponseCode(); 

        if (responseCode == HttpsURLConnection.HTTP_OK) { 

         BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream())); 
         StringBuilder sb = new StringBuilder(""); 
         String line=""; 
         while ((line = in.readLine()) != null) 
         { 
          sb.append(line).append("\n"); 
         } 
         result = sb.toString(); 
        } 

        assert inputStream != null; 
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
        StringBuilder sb = new StringBuilder(); 

        String line = null; 
        while ((line = reader.readLine()) != null) 
        { 
         sb.append(line).append("\n"); 
        } 
        result = sb.toString(); 
       } catch (Exception e) { 
        Log.i("tagconvertstr", "["+result+"]"); 
        System.out.println(e); 
       } 
       finally { 
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){} 
       } 
       return result; 
      } 

      @Override 
      protected void onPostExecute(String result){ 

       myJSON = result; 
       showList(); 

      } 
     } 
     GetDataJSON g = new GetDataJSON(); 
     g.execute(); 
    } 



    protected void showList(){ 
     try { 
      peoples = new JSONArray(myJSON); 
      for(int i=0;i<peoples.length();i++){ 

       JSONObject c = peoples.getJSONObject(i); 
       String name = c.getString(TAG_NAME); 

       HashMap<String,String> persons = new HashMap<String,String>(); 

       persons.put(TAG_NAME,name); 

       personList.add(persons); 
      } 



      ListAdapter adapter = new SimpleAdapter(
        ListViewMultipleSelectionActivity.this, personList, R.layout.result, 
        new String[]{TAG_NAME}, 
        new int[]{R.id.name} 
      ); 




      list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
      list1.setAdapter(adapter); 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

    } 



} 

main.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <Button 
     android:id="@+id/testbutton" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:text="Submit" /> 

    <ListView 
     android:id="@+id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_above="@id/testbutton" 
     android:layout_alignParentTop="true"/> 

</RelativeLayout> 

result.xml

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

<CheckBox 
    android:id="@+id/cbBox" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center_vertical" > 
</CheckBox> 

<LinearLayout 
    android:id="@+id/linearLayout1" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="5dp" 
    android:orientation="vertical" 
    android:layout_weight="1" > 

    <TextView 
     android:id="@+id/name" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingBottom="2dip" 
     android:textStyle="bold"/> 

</LinearLayout> 

</LinearLayout> 

ある

をご確認ください。
button.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       SparseBooleanArray checked = list1.getCheckedItemPositions(); 
       ArrayList<String> selectedItems = new ArrayList<String>(); 
       for (int i = 0; i < checked.size(); i++) { 
        int position = checked.keyAt(i); 
         if (checked.valueAt(i)) 
         selectedItems.add((String) adapter.getItem(position)); 
       } 

       String[] valuess = new String[selectedItems.size()]; 

       for (int i = 0; i < selectedItems.size(); i++) { 
        valuess[i] = selectedItems.get(i); 
       } 
       Toast.makeText(ListViewMultipleSelectionActivity.this, String.valueOf(valuess), Toast.LENGTH_SHORT).show(); 
      } 
     }); 

これは私がした後、あなたのアダプタのgetViewメソッド()メソッドであなたの「convertView」であるかもしれないあなたの行のビューにタグとして

E/-->>>>: [Ljava.lang.String;@ca01299 
+2

の可能性のある重複http://stackoverflow.com/questions/19027843/android-get-text-of-all-checked-checkboxes-in([すべてのアンドロイドのgetテキストは、ListViewコントロールのチェックボックスをチェックします] -listview) –

+0

あなたのテストボタンのすべてのチェックされた値をクリックしますか? –

+0

はい、testbuttonをクリックすると、チェックされているlistviewのすべての値が必要です –

答えて

0
  1. 設定]チェックボックスオブジェクトをクリックし取得しています。

  2. 行ビューのクリックリスナーに書き込みます。 3.クリックリスナーの横に、onClickメソッドのパラメータであるビューからgetTagをビューし、そのチェックボックスオブジェクトに対してcheckboxにキャストしてからsetCheckedをtrueに設定します。

コードが

convertView.setTag(yourCheckBoxObject); 
    convertView.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      CheckBox cb = (CheckBox) v.getTag(); 
      cb.setChecked(true); 
     } 
    }); 

getViewメソッド(と呼ばれる1つの@Overrideメソッドがあったあなたのアダプタではより多くの情報のためGetting an issue while checking the dynamically generated checkbox through list view

0

をこの光景を参照してください、次のようになります)その方法で必要になりますあなたがクリックする現在のアイテムを取得する

holder.checkbox.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

    CheckBox checkBox=(CheckBox) view; 
     String tagName=""; 
    if(checkBox.isChecked()){ 
     tagName=checkBox.getTag().toString(); 
     deleteServices.add(tagName); 
     checkboxArrayList.add(checkBox); 
    }else { 
      checkboxArrayList.remove(checkBox); 
      tagName=checkBox.getTag().toString(); 
       if(deleteServices.size()>0&&deleteServices.contains(tagName)){ 

deleteService s.remove(tagName); }それをサポートするカスタムアダプタと一緒に、これらの値を格納するカスタムクラスを作成して何ができる

 }); 
1

。したがって、ボタンをクリックするたびに、指定された関数を呼び出してそれらの項目のステータスを取得することができます。以下に与えられるアーキテクチャの例

PS:あなたがチェックされた値で何をしたいのか分からないので、必要に応じてコメントを残しました。

MainActivity.java

package com.rencsaridogan.stackoverflow; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ListView; 
import java.util.ArrayList; 

public class MainActivity extends AppCompatActivity { 

    ArrayList<ExampleClass> objects; 

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

    objects = new ArrayList<>(); 

    for (int i = 0; i < 10; i++){ 
     objects.add(new ExampleClass("Example Name " + i)); 
    } 

    final ListView listView = (ListView) findViewById(R.id.listView); 
    final Button testButton = (Button) findViewById(R.id.testButton); 
    final ExampleAdapter exampleAdapter = new ExampleAdapter(this, R.layout.list_cell, objects); 
    listView.setAdapter(exampleAdapter); 
    exampleAdapter.notifyDataSetChanged(); 

    testButton.setOnClickListener(new View.OnClickListener() { 
     @Override public void onClick(View v) { 
     getCheckedItems(); 
     } 
    }); 

    } 

    private void getCheckedItems(){ 
    for (int i = 0; i < 10; i++) { 
     if (objects.get(i).isChecked()){ 
     Log.i("MainActivity",i + " is checked"); 
     /** 
     * Value is checked, do what you need to do here 
     */ 
     } else { 
     Log.i("MainActivity",i + " is NOT checked"); 
     /** 
     * Value is NOT checked 
     */ 
     } 
    } 
    } 
} 

ExampleAdapter.java

package com.rencsaridogan.stackoverflow; 

import android.annotation.SuppressLint; 
import android.content.Context; 
import android.support.annotation.NonNull; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.CheckBox; 
import android.widget.CompoundButton; 
import android.widget.TextView; 
import java.util.ArrayList; 
/** 
* Created by rencsaridogan on 16/02/2017. 
*/ 

public class ExampleAdapter extends ArrayAdapter<ExampleClass> { 

    ArrayList<ExampleClass> objects; 
    Listener listener; 
    Context context; 

    public ExampleAdapter(Context context, int resource, ArrayList<ExampleClass> objects) { 
    super(context, resource); 
    this.context = context; 
    this.objects = objects; 
    } 

    @Override public int getViewTypeCount() { 
    return super.getViewTypeCount(); 
    } 

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

    @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { 

    if (convertView == null){ 
     Log.i("ExampleAdapter","ConvertView inflated"); 
     convertView = LayoutInflater.from(context).inflate(R.layout.list_cell, null, false); 
    } 

    Log.i("ExampleAdapter","Setting of values"); 

    final ExampleClass data = objects.get(position); 
    final ViewHolder viewHolder = new ViewHolder(); 

    viewHolder.textView = (TextView) convertView.findViewById(R.id.textView); 
    viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox); 

    viewHolder.textView.setText(data.getName()); 

    viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     data.setChecked(isChecked); 
     } 
    }); 

    return convertView; 
    } 

    public void setListener(Listener listener) { 
    this.listener = listener; 
    } 

    private class ViewHolder { 

    TextView textView; 
    CheckBox checkBox; 
    } 

    public ArrayList<ExampleClass> getObjects() { 
    return objects; 
    } 

    public void setObjects(ArrayList<ExampleClass> objects) { 
    this.objects = objects; 
    notifyDataSetChanged(); 
    } 

    @Override public long getItemId(int position) { 
    return super.getItemId(position); 
    } 

    public interface Listener { 
    void onCheckedChanged(int position); 
    } 
} 

でExampleClass。Javaの

package com.rencsaridogan.stackoverflow; 

/** 
* Created by rencsaridogan on 16/02/2017. 
*/ 

public class ExampleClass { 
    String name; 
    boolean isChecked; 

    public ExampleClass(String name) { 
    this.name = name; 
    } 

    public ExampleClass(String name, boolean isChecked) { 
    this.name = name; 
    this.isChecked = isChecked; 
    } 

    public String getName() { 
    return name; 
    } 

    public void setName(String name) { 
    this.name = name; 
    } 

    public boolean isChecked() { 
    return isChecked; 
    } 

    public void setChecked(boolean checked) { 
    isChecked = checked; 
    } 
} 
関連する問題