2016-03-28 36 views
0

我有一个从JSON获取数据的列表视图。到目前为止,我能够以列表视图显示数据。 (这里的数据是代理商列表)。 现在我想开当特定剂被点击,这将显示代理细节,如姓名,电话,电子邮件等列表视图的新活动....如何在列表视图中显示与点击项目相关的数据? (onclicklistener)

,因为我是新来的Android我将不胜感激任何想法。

我的代码:

public class MainActivity extends AppCompatActivity 

{

private String jsonResult; 
public String url = "http://111.111.111.1/androidapp/getjson.php"; 
ListView listView; 
List<Map<String, String>> agents = new ArrayList<Map<String, String>>(); 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    listView = (ListView) findViewById(R.id.listView); 
    accessWebService(); 
} 
private class JsonReadTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... params) 
    { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(params[0]); 
     try { 
      HttpResponse response = httpclient.execute(httppost); 
      jsonResult = inputStreamToString(
        response.getEntity().getContent()).toString(); 

     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    private StringBuilder inputStreamToString(InputStream is) { 
     String rLine = ""; 
     StringBuilder answer = new StringBuilder(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     try { 
      while ((rLine = rd.readLine()) != null) { 
       answer.append(rLine); 
      } 
     } catch (IOException e) { 
      Toast.makeText(getApplicationContext(), "error ..." + e.toString(), Toast.LENGTH_LONG).show(); 
     } 
     return answer; 
    } 

    @Override 
    protected void onPostExecute(String result) 
    { 
     ListDrwaer(); 
    } 
} 

public void accessWebService() { 
    JsonReadTask task = new JsonReadTask(); 
    task.execute(new String[]{url}); 
} 

public void ListDrwaer() { 
    try { 
     JSONObject jsonResponse = new JSONObject(jsonResult.substring(jsonResult.indexOf("{"), jsonResult.lastIndexOf("}") + 1)); 
     JSONArray jsonMainNode = jsonResponse.optJSONArray("agents"); 

     final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>(); 
     HashMap<String, String> map; 

     for (int i = 0; i < jsonMainNode.length(); i++) { 
      JSONObject c = jsonMainNode.getJSONObject(i); 

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

      map.put("AgtFirstName", c.getString("AgtFirstName")); 
      map.put("AgtLastName", c.getString("AgtLastName")); 

      MyArrList.add(map); 

      SimpleAdapter simpleAdapter; 
      simpleAdapter = new SimpleAdapter(MainActivity.this, MyArrList, R.layout.activity_column, new String[]{"AgtFirstName", "AgtLastName"}, new int[]{R.id.AgtFirstName , R.id.AgtLastName}); 

      listView.setAdapter(simpleAdapter); 
     } 
    } catch (JSONException e) { 
     Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show(); 
    } 
} 



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



@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    int id = item.getItemId(); 

      if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() 
{ 
    public void onItemClick(AdapterView<?> parent,View view, int position, long id) 
    { 
     Intent i=new Intent(MainActivity.this,AgentDetails.class); 
     i.putExtra("position", map.get(position)); 
     startActivity(i); 

    } 
}; 

}

+0

只要你可以获取数据onitem点击并通过intent发送 –

+0

@ Poovizhirajan.N我使用onItemClick但数据不显示在其他活动 –

回答

0

以下是你可以利用两个选项。

1)设置OnItemClick,它将触发相应ListView条目中的任何组件(位置指示哪个特定的条目已被选中)(OnItemLongClick也可以类似的方式使用)。

2)来设置的OnClick监听用于一个ListView内的特定视图。这允许在Listview条目中具体操作不同的元素/视图。

比如我有一个包含若干个TextViews的,其中有两个我要采取行动(标示完成和删除)仿佛Textviews是按钮的ListView控件。有了这些,我在XML中设置了onClick。与此问题是你不知道哪个条目(即没有位置,解决方案使用setTags)。我也有OnItemClick。所以点击其他地方允许其他选项/操作。

代码为1(其他操作),其中shoppinglistlv是ListView控件(注位置如何可用),这是在onCreate方法: -

shoppinglistlv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       Toast.makeText(view.getContext(), "ListView clicked", Toast.LENGTH_SHORT).show(); 
      } 
     }); 

对于2,我有: -

public void sledelete(View view) { 
     Integer tag = (Integer)view.getTag(); 
     shoppinglistcsr.moveToPosition(tag); 
     shopperdb.setShopListEntryAsComplete(shoppinglistcsr.getLong(0)); 
     shoppinglistcsr = shopperdb.getShoppingList(); 
     currentsla.swapCursor(shoppinglistcsr); 
    } 
public void slareorg(View view) { 
     shopperdb.reorgShopList(); 
     shoppinglistcsr = shopperdb.getShoppingList(); 
     currentsla.swapCursor(shoppinglistcsr); 
    } 

随着(需要注意的onClick的导致上述方法被调用,setTag在适配器的bindView完成)。这是从XML为ListView项,而不是ListView控件本身: -

 <TextView 
      android:id="@+id/shoppinglist_donebutton" 
      android:layout_width="@dimen/standard_dummy_size" 
      android:layout_height="@dimen/standard_subsubsubheading_height" 
      android:layout_weight="0.05" 
      android:singleLine="true" 
      android:text="@string/standarddonebutton" 
      android:gravity="center" 
      android:textSize="@dimen/standard_subsubsubheading_text_size" 
      android:textStyle="bold" 
      android:background="@color/colorNormalButton" 
      android:textColor="@color/colorNormalButtonText" 
      android:onClick="sledone"/> 
     <TextView 
      android:layout_width="@dimen/standard_dummy_size" 
      android:layout_height="match_parent" 
      android:layout_weight="0.005"/> 
     <TextView 
      android:id="@+id/shoppinglist_deletebutton" 
      android:layout_width="@dimen/standard_dummy_size" 
      android:layout_height="@dimen/standard_subsubsubheading_height" 
      android:layout_weight="0.05" 
      android:singleLine="true" 
      android:text="@string/standarddeletetext" 
      android:gravity="center" 
      android:textSize="@dimen/standard_subsubsubheading_text_size" 
      android:textStyle="bold" 
      android:background="@color/colorRequiredLabel" 
      android:textColor="@color/colorNormalButtonText" 
      android:onClick="sledelete"/> 

随着这在adpater的bindView(设置的标签位置)注donebtntv和deletebtntv拿着各自的TextView的id: -

// Set tags to enable onClick to determine the cursor position of the clicked entry 
donebtntv.setTag(Integer.valueOf(pos)); 
deletebtntv.setTag(Integer.valueOf(pos)); 

最后,在ListView的XML根我也有: -

android:descendantFocusability="afterDescendants" 

(我不知道这是否是必需的,但我得到两种类型,1 & 2以上,用此处理)

这可能过于复杂,但会显示一些选项。

下面是OnItemClick一些示例代码启动等活动,取决于对话选择。这显示了如何通过意向附加功能传递数据: -

// Click on an Aisle to update the Aisle or Stock the Aisle 
     aisleslistview = (ListView) findViewById(R.id.aalbclv01); 
     aisleslistview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

       AlertDialog.Builder okdialog = new AlertDialog.Builder(view.getContext()); 
       okdialog.setTitle(getString(R.string.aislelistclicktitle)); 
       okdialog.setMessage(getString(R.string.aislelistclicktext001)); 
       okdialog.setCancelable(true); 
       okdialog.setPositiveButton(getString(R.string.standardedittext), new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         resume_state = RESUMESTATE_AISLEUPDATE; 
         Intent intent = new Intent(findViewById(R.id.aalbclv01).getContext(), AisleAddActivity.class); 
         AislesCursorAdapter aisleadapter = (AislesCursorAdapter) ((ListView) findViewById(R.id.aalbclv01)).getAdapter(); 
         intent.putExtra("Caller", THIS_ACTIVITY + "Update"); 
         intent.putExtra("AisleID", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ID_INDEX)); 
         intent.putExtra("AISLEID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_ID_INDEX)); 
         intent.putExtra("AisleName", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX)); 
         intent.putExtra("AisleOrder", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX)); 
         intent.putExtra("AisleShopRef", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX)); 
         intent.putExtra("SHOPID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX)); 
         startActivity(intent); 
         dialog.cancel(); 
        } 
       }); 
       okdialog.setNegativeButton(getString(R.string.standardstockaisletext), new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         resume_state = RESUMESTATE_AISLESTOCK; 
         Intent intent = new Intent(findViewById(R.id.aalbclv01).getContext(), AddProductToShopActivity.class); 
         AislesCursorAdapter aisleadapter = (AislesCursorAdapter) ((ListView) findViewById(R.id.aalbclv01)).getAdapter(); 
         intent.putExtra("Caller", THIS_ACTIVITY + "Stock"); 
         intent.putExtra("AisleID", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ID_INDEX)); 
         intent.putExtra("AISLEID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_ID_INDEX)); 
         intent.putExtra("AisleName", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX)); 
         intent.putExtra("AisleOrder", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX)); 
         intent.putExtra("AisleShopRef", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX)); 
         intent.putExtra("AISLESHOPREF", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX)); 
         intent.putExtra("SHOPID",aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX)); 
         startActivity(intent); 
         dialog.cancel(); 
        } 
       }); 
       okdialog.setNeutralButton(getString(R.string.standardbacktext), new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         resume_state = RESUMESTATE_NOTHING; 
         dialog.cancel(); 
        } 
       }); 
       okdialog.show(); 
      } 
     }); 

注意!以上是使用SQlite/Cursors作为列表源数据。但是,这些技术应该是相似的。

+0

感谢迈克我从mySQL获取数据,所以它是如何工作的?我读了几个教程,但他们不适合我。你能具体吗? –

+0

@ Poovizhirajan.N我没有通过JSON使用MySQL数据。然而,它看起来好像你会用位置来获取各自的数组列表/成员,然后使用map.get(“AgtFirstName”)等。因此,你可以有一些沿着map = MyArrList(position)的行,然后是intent .putExtra( “姓”,map.get( “AgtFirstName”));在startActivity之前,然后在被调用的活动中分别进行额外的检索。例如String firstname = getIntent()。getStringExtra(“FirstName”) – MikeT

+0

谢谢!我会尝试... –

相关问题