2014-11-17 6 views
0

Привет, я новичок в android, в моем приложении я получаю более одного списка пользователей в Listview, используя json, и у него есть один уникальный идентификатор, который выглядит так.Как отправить идентификатор от фрагмента к активности?

Я получаю эти данные совершенно в моих приложениях, теперь в этом json я matching_id, которые уникальны теперь я хочу, чтобы получить профиль пользователя в соответствии с этим идентификатором во второй странице и ее json выглядит это позволяет принимать id=636 так я хочу получить подробности ..

Homefragment класс

public class HomeFragment extends ListFragment { 

    //CustomAdapter adapter; 
    //private List<RowItem> rowItems; 

    private ProgressDialog pDialog; 
    //JSON parser class 
    JSONParser jsonParser = new JSONParser(); 

    JSONArray matching=null; 

    ArrayList<HashMap<String,String>> aList; 
    private static String MATCH_URL = null; 
    private static final String TAG_MATCH="matching"; 
    private static final String TAG_MATCH_ID="match_detail_id"; 
    private static final String TAG_NAME="name"; 
    private static final String TAG_PROFILE="profile_id"; 
    private static final String TAG_IMAGE="image"; 
    private static final String TAG_CAST="cast"; 
    private static final String TAG_AGE="age"; 
    private static final String TAG_LOCATION="location"; 

    private ListView listview; 

    public HomeFragment(){} 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 

     String strtext = getArguments().getString("user_login_id"); 
     MATCH_URL = "http://abcsd.com/webservice/matching?version=apps&user_login_id="+strtext; 
     View rootView = inflater.inflate(R.layout.fragment_home, container, false); 
     aList = new ArrayList<HashMap<String,String>>(); 

     // rowItems = new ArrayList<RowItem>(); 

     listview=(ListView)rootView.findViewById(android.R.id.list); 

     new LoadAlbums().execute(); 



     return rootView; 
    } 

    class LoadAlbums extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(HomeFragment.this.getActivity()); 
      pDialog.setMessage("Loading..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 
     protected String doInBackground(String... args) { 
      ServiceHandler sh = new ServiceHandler(); 

      // Making a request to url and getting response 
      String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET); 

      Log.d("Response: ", "> " + jsonStr); 

      if (jsonStr != null) { 
       try { 
        JSONObject jsonObj = new JSONObject(jsonStr); 

        // Getting JSON Array node 
        matching = jsonObj.getJSONArray(TAG_MATCH); 

        // looping through All Contacts 
        for (int i = 0; i < matching.length(); i++) { 
         JSONObject c = matching.getJSONObject(i); 




         // Storing each json item values in variable 
         String user_match_id=c.getString(TAG_MATCH_ID); 
         String user_name = c.getString(TAG_NAME); 
         String user_profile=c.getString(TAG_PROFILE); 
         String user_image=c.getString(TAG_IMAGE); 
         String user_cast=c.getString(TAG_CAST); 
         String user_age=c.getString(TAG_AGE); 
         String user_location=c.getString(TAG_LOCATION); 



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

         // adding each child node to HashMap key => value 
         map.put(TAG_MATCH_ID, user_match_id); 
         map.put(TAG_NAME,user_name); 
         map.put(TAG_PROFILE, user_profile); 
         map.put(TAG_IMAGE, user_image); 
         map.put(TAG_CAST, user_cast); 
         map.put(TAG_AGE, user_age+" years"); 
         map.put(TAG_LOCATION, user_location); 



         // adding HashList to ArrayList 
         aList.add(map); 


        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } else { 
       Log.e("ServiceHandler", "Couldn't get any data from the url"); 
      } 

      return null; 
     } 


     protected void onPostExecute(String file_url) { 

      super.onPostExecute(file_url); 
      // dismiss the dialog after getting all albums 
      if (pDialog.isShowing()) 
      pDialog.dismiss(); 
      // updating UI from Background Thread 

        /** 
        * Updating parsed JSON data into ListView 
        * */ 
      CustomAdapter adapter = new CustomAdapter(getActivity(),aList); 
      setListAdapter(adapter); 

       } 

     } 




} 

это теперь работает нормально в следующей деятельности я хочу, чтобы получить полную информацию, как в секунду json.

Активность ниже Активность Я хочу получить подробную информацию о пользователях Что я должен делать?

public class ProfilePage extends Activity{ 

private ImageView cover; 
private ImageView yes; 
private ImageView no; 
private ImageView sendmsg; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.profile_page); 

    cover=(ImageView)findViewById(R.id.coverimage); 
    yes=(ImageView)findViewById(R.id.yesbutton); 
    no=(ImageView)findViewById(R.id.nobutton); 
    sendmsg=(ImageView)findViewById(R.id.imgsendmsgg); 
    sendmsg.setOnClickListener(new OnClickListener() 
    { 

     @Override 
     public void onClick(View arg0) 
     { 
      AlertDialog.Builder builder = new AlertDialog.Builder(ProfilePage.this); 
      builder.setTitle(R.string.title_alertbox_upgrade) 
        .setIcon(R.drawable.ic_launcher) 
        .setMessage(R.string.chek_upgrade) 
        .setCancelable(true) 
        .setNegativeButton(R.string.okalert_upgrade, new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          dialog.dismiss(); 
         } 
        }); 

      AlertDialog welcomeAlert = builder.create(); 
      welcomeAlert.show(); 
      // Make the textview clickable. Must be called after show() 
      ((TextView)welcomeAlert.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); 
      /*// Creating alert Dialog with one Button 

      AlertDialog alertDialog = new AlertDialog.Builder(
        ProfileEdit.this).create(); 

      // Setting Dialog Title 
      alertDialog.setTitle("Edit Profile"); 

      // Setting Dialog Message 
      alertDialog.setMessage("Please log on to gujjumatch.com desktop site to edit your profile " + 
        "and also set other details or call on 91 281 3054120"); 

      // Setting Icon to Dialog 
      alertDialog.setIcon(R.drawable.ic_launcher); 

      // Setting OK Button 
      alertDialog.setButton("OK", 
        new DialogInterface.OnClickListener() { 

         public void onClick(DialogInterface dialog, 
           int which) { 
          // Write your code here to execute after dialog 
          // closed 
          Toast.makeText(getApplicationContext(), 
            "Thank You", Toast.LENGTH_SHORT) 
            .show(); 
         } 
        }); 

      // Showing Alert Message 
      alertDialog.show();*/ 


     } 
    }); 
    yes.setOnClickListener(new OnClickListener() 

    { 

     @Override 
     public void onClick(View arg0) { 

      LayoutInflater inflater = getLayoutInflater(); 


      View layout = inflater.inflate(R.layout.custom_toast, 
         (ViewGroup) findViewById(R.id.custom_toast_layout_id)); 

      ImageView image = (ImageView) layout.findViewById(R.id.image); 
      image.setImageResource(R.drawable.yes); 

      // set a message 
      TextView text = (TextView) layout.findViewById(R.id.text); 
      text.setText("Interest Sent"); 



      // Toast... 
      Toast toast = new Toast(getApplicationContext()); 
      toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
      toast.setDuration(Toast.LENGTH_LONG); 
      toast.setView(layout); 
      toast.show(); 

     } 
    }); 

    no.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 

      LayoutInflater inflater = getLayoutInflater(); 


      View layout = inflater.inflate(R.layout.custom_toast, 
         (ViewGroup) findViewById(R.id.custom_toast_layout_id)); 

      ImageView image = (ImageView) layout.findViewById(R.id.image1); 
      image.setImageResource(R.drawable.no); 

      // set a message 
      TextView text = (TextView) layout.findViewById(R.id.text1); 
      text.setText("Interest Declined"); 



      // Toast... 
      Toast toast = new Toast(getApplicationContext()); 
      toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
      toast.setDuration(Toast.LENGTH_LONG); 
      toast.setView(layout); 
      toast.show(); 

     } 
    }); 
    cover.setOnClickListener(new OnClickListener() { 
        @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      // Sending image id to FullScreenActivity 
       Intent i = new Intent(getApplicationContext(), Fullimage.class); 
       // passing array index 


       startActivity(i); 

     } 
    }); 
} 

} 
+0

интерфейс делают для и сделать метод в нем и вызывать этот метод в вашем фрагменте после реализует свой фрагмент с интерфейсом и его обратного вызова. – Piyush

ответ

0

Это ваш ListView в классе фрагмента.

Я предполагаю, что вы можете создать ListView с легкостью ...

Теперь при щелчке ListView вам нужно передать данные, как это ..

lv.setOnItemClickListener(new OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1, 
        int arg2, long arg3) { 
     Intent intent = new Intent(getActivity(), UserBrandsFragmentDetail.class); 
     intent.putExtra("brand_logo", m_ArrayList.get(arg2).brand_logo); 
     startActivity(intent); 
    } 
} 

UPDATE

Вам требуется иметь ListView. Затем, нажав ListView, вы должны использовать мой вышеупомянутый код ...

В моем вышеупомянутом коде «lv» есть ListView. :)

В вашей следующей деятельности вам необходимо получить эти данные с помощью пакета ... вот так.

Bundle extra = getIntent().getExtras(); 
String your_data = extra.getString("your_key_while_parsing_data_through_Intent"); 

Вот и все .. вам хорошо идти!

Для создания списка списка вы можете использовать его в Google. Для этого доступно много учебников.

Позвольте мне знать, если вы все еще есть какие-то запрос ..

+0

проверить мой вопрос и дать краткое описание –

0

Начать новую деятельность/Fragment в onitemclick из ListView и Пропустите "match_detail_id" в дополнительных.

Если вы используете деятельность use putExtra и getExtra. При использовании Используйте ФРАГМЕНТ

Bundle bundle = new Bundle(); 
fragment.setArguments(bundle); 

и

fragment.getArguments() //in oncreate of fragment. 

и получить полную информацию в OnCreate деятельности/Фрагмент

Смежные вопросы