-1

这是我的代码,它在列表视图中显示 JSON 属性。我在列表视图中仅显示“名称”,我想将其他属性作为参数传递给其他活动。下面是我的代码,我只想在列表视图中显示名称“星期一、星期二、星期三”。当用户单击“dish、Gender、age”等其他值时,将作为参数传递给其他 Activity。我该怎么做?

{
"student": [
    {
        "id": 1,
        "name": "Monday",
        "dish": "Biryani",
        "Gender": "M",
        "age": 10,
        "birthdate": "23/05/2002"
    },
    {
        "id": 2,
        "name": "Tuesday",
        "dish": "Sandwish",
        "Gender": "M",
        "age": 12,
        "birthdate": "08/01/2000"
    },
    {
        "id": 3,
        "name": "Wednesday",
        "dish": "Chicken Tikka",
        "Gender": "F",
        "age": 14,
        "birthdate": "01/03/1998"
    },





public class SeletecDayofweek extends Activity implements   
   OnItemClickListener {

private static final String rssFeed = "https://www.dropbox.com/s/rhk01nqlyj5gixl 
   /jsonparsing.txt?dl=1";

private static final String ARRAY_NAME = "student";
private static final String ID = "id";
private static final String NAME = "name";
private static final String CITY = "dish";
private static final String GENDER = "Gender";
private static final String AGE = "age";
private static final String BIRTH_DATE = "birthdate";


   ListView listMainMenu;
    List<Item> arrayOfList;
//MainMenuAdapter mma;
NewsRowAdapter objAdapter;
String myname;
JSONObject objJson ;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.selectdayofweek);

    listMainMenu = (ListView) findViewById(R.id.listMainMenu2);
    listMainMenu.setOnItemClickListener(this);

    arrayOfList = new ArrayList<Item>();

     if (URLUtils.isNetworkAvailable(SeletecDayofweek.this)) {
        new MyTask().execute(rssFeed);
    } else {
        showToast("No Network Connection!!!");
    }

}

// My AsyncTask start...

class MyTask extends AsyncTask<String, Void, String> {

    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(SeletecDayofweek.this);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        return URLUtils.getJSONString(params[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (null == result || result.length() == 0) {
            showToast("No data found from web!!!");
            SeletecDayofweek.this.finish();
        } else {

            try {
                JSONObject mainJson = new JSONObject(result);
                JSONArray jsonArray = 
            mainJson.getJSONArray(ARRAY_NAME);
                for (int i = 0; i < jsonArray.length(); i++) {
                     objJson = jsonArray.getJSONObject(i);

                    Item objItem = new Item();

                    objItem.setId(objJson.getInt(ID));
                    objItem.setName(objJson.getString(NAME));
                    myname= objJson.getString(NAME);
                    objItem.setCity(objJson.getString(CITY));

  objItem.setGender(objJson.getString(GENDER));
                    objItem.setAge(objJson.getInt(AGE));

        objItem.setBirthdate(objJson.getString(BIRTH_DATE));

                    arrayOfList.add(objItem);

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

            setAdapterToListview();

        }

    }
}

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



}


public void setAdapterToListview() {
    objAdapter = new NewsRowAdapter(SeletecDayofweek.this,   
   R.layout.main_menu_item,
            arrayOfList);
    listMainMenu.setAdapter(objAdapter);
}

public void showToast(String msg) {
    Toast.makeText(SeletecDayofweek.this, msg, Toast.LENGTH_LONG).show();
}

  }






                             public class NewsRowAdapter extends ArrayAdapter<Item> {

private Activity activity;
private List<Item> items;
private Item objBean;
private int row;
Context context;

public NewsRowAdapter(Activity act, int resource, List<Item> arrayList) {
    super(act, resource, arrayList);
    this.activity = act;
    this.row = resource;
    this.items = arrayList;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    ViewHolder holder;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(row, null);

        holder = new ViewHolder();
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    if ((items == null) || ((position + 1) > items.size()))
        return view;

    objBean = items.get(position);

    holder.tvName = (TextView) view.findViewById(R.id.txtText);


    if (holder.tvName != null && null != objBean.getName()
            && objBean.getName().trim().length() > 0) {
        holder.tvName.setText(Html.fromHtml(objBean.getName()));


    }


    return view;
}

public class ViewHolder {
    public TextView tvName, tvCity, tvBDate, tvGender, tvAge;
}
 }




                   public class Item {
private int id;
private String name;
private String city;
private String gender;
private int age;
private String birthdate;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public String getBirthdate() {
    return birthdate;
}

public void setBirthdate(String birthdate) {
    this.birthdate = birthdate;
}
}
4

2 回答 2

0
  1. JSON通过仅解析一次,创建一个单独的类,该类具有对应于单个学生的字段的字段。填充列表视图时,您可以通过创建此类的自定义适配器并覆盖toString()仅返回名称的函数来仅显示名称。
  2. 当您移动到下一个活动时,只需根据列表中的所选项目将所选对象传递给下一个活动。

PS:- 这个解决方案可能需要一些时间来编写代码,但它利用了 Java 的面向对象特性,并且在技术上是合理的


编辑1:

在我的示例中,我使用了具有不同字段集的学生课程!

1)为您的学生对象创建一个自定义类。

StudentDataForAttendance.java

package com.kaavay.attendanceapplication.data;

import android.annotation.SuppressLint;
@SuppressLint("DefaultLocale")
public class StudentDataForAttendance implements
    Comparable<StudentDataForAttendance> {
private final String    rollno;
private final String    name;
private final String    uniqueST;
private String       attendance;

public StudentDataForAttendance(final String rollno, final String name,
        final String uniqueST, final String attendance) {
    super();
    this.rollno = rollno;
    this.name = name;
    this.uniqueST = uniqueST;
    this.attendance = attendance;
}

@Override
public int compareTo(final StudentDataForAttendance another) {
    final String rollno1 = getRollno().toUpperCase();
    final String rollno2 = another.getRollno().toUpperCase();
    // ascending order
    return rollno1.compareTo(rollno2);
}

@Override
public boolean equals(final Object o) {
    final StudentDataForAttendance sdfa = (StudentDataForAttendance) o;
    if (sdfa.getUniqueST().equals(getUniqueST()))
        return true;
    else
        return false;
}

/**
 * @return the attendance
 */
public String getAttendance() {
    return attendance;
}

/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @return the rollno
 */
public String getRollno() {
    return rollno;
}

/**
 * @return the uniqueST
 */
public String getUniqueST() {
    return uniqueST;
}

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

public void setAttendance(final String string) {
    // TODO Auto-generated method stub
    attendance = string;
}

/*
 * (non-Javadoc)
 * 
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    return "StudentDataForAttendance [name=" + name + "]";
}
}

2)在您的活动中创建一个AsyncTask解析JSON文件并在循环内创建学生对象并将其存储在活动中定义的类型的静态对象数组StudentDataForAttendance中的活动。

3)在填充您的列表活动代码时,如下所示:

final StudentListAdapter studentAdapter = new StudentListAdapter(this,
            android.R.layout.simple_list_item_1, R.id.lvStudentAttendance,
            studentData);
    lvStudentAttendance.setAdapter(studentAdapter);

StudentListAdapter如下:

public class StudentListAdapter extends BaseAdapter {
private List<StudentDataForAttendance>  studentData = new ArrayList<StudentDataForAttendance>();
Context                                context;
int                                    listViewResourceId;

public StudentListAdapter(final Context context, final int resource,
        final int textViewResourceId,
        final StudentDataForAttendance[] studentData) {
    super();
    // Log.d("Constructor", "Run");
    this.studentData = Arrays.asList(studentData);
    this.context = context;
    listViewResourceId = textViewResourceId;
}

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

@Override
public Object getItem(final int position) {
    return studentData.get(position).getName();
}

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

@Override
public View getView(final int position, final View convertView,
        final ViewGroup parent) {
    //You can put any data to your rows of the list here is there is a need to
            //display more than just names in your case!!!! What i have used
            //is custom layout for each of the rows
    View v = null;
    // For reusing cells when out of view
    if (convertView == null) {
        final LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.custom_cell_student_list, parent,
                false);
    }
    else
        v = convertView;
    //
            //
    //What i have coded here is not important to your question
            //
            //
            //
            //
    return v;
}
}

这才是正确的做法!


*编辑 2:为了让对象点击你所做的是在这个方法中

public void onItemClick(final AdapterView<?> av, final View v,
        final int position, final long id)

获取对象

final StudentDataForAttendance clickedStudent = studentData[position];

并使用它将它传递给下一个活动,studentData我的静态对象数组在哪里,由来自JSON

于 2013-07-01T05:54:04.217 回答
0

使用 Intent Extras 如下:

单击 listItem 时,获取 listitem 并存储在 String 中并将其传递给 otherscreen,如下所示:

 @Override
 public void onItemClick(AdapterView<?> parent, View view, int position,
    long id) {
      Intent i = new Intent(CurrentClass.this, TargetClass.class);
 i.putExtra("WEEK_DAY", ((TextView) view.findViewById(R.id.listrow_id).getText().toString());
 i.putExtra("WEEK_DISH", dish_data);
 i.putExtra("AGE", age);
 startActivity(i);
 }

并在其他活动中获取数据,

Intent  i= getIntent();
String week_day = i.getStringExtra("WEEK_DAY");
String week_dish = i.getStringExtra("WEEK_DISH");
String week_age = i.getStringExtra("AGE");
于 2013-07-01T05:55:50.187 回答