2015-05-07 2 views
1

В ParseQueryAdapter Я хочу вернуть отношение объекта, который я запрашиваю. Это то, что у меня есть до сих пор; Я выполняю запрос, получая все цели, созданные текущим пользователем; in public View getItemView Я начинаю получать отношение объекта (цели). Создать ли цикл for и сохранить результаты в массиве? Если да, то как я могу установить текст в списке? Большое спасибо за Вашу помощь!Parse, Android; Отношение.getQuery() в ParseQuery Adapter

public class GoalDetailViewAdapter extends ParseQueryAdapter<ParseObject> { 

    protected ParseObject mPracticeName; 



    public GoalDetailViewAdapter(Context context) { 




     super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() { 

      public ParseQuery create() { 
       // Here we can configure a ParseQuery to display 
       // midwives 
       ParseQuery<ParseObject> query = ParseQuery.getQuery("goal"); 
       query.whereEqualTo("createdby", ParseUser.getCurrentUser()); 

       return query; 
      } 
     }); 
    } 



    @Override 
    public View getItemView(ParseObject object, View view, final ViewGroup parent) { 

     if (view == null) { 
      view = View.inflate(getContext(), R.layout.activity_goal_detail_view, null); 

     } 

     //use midwifefirm as item view/list 

     super.getItemView(object, view, parent); 


     // find in layout the practice name 
     TextView titleTextView = (TextView) view.findViewById(R.id.goalname); 

     //in the midwifefirm data model, call getPracticename 
     titleTextView.setText(object.getString("goalname")); 


     TextView practiceTextView = (TextView) view.findViewById(R.id.practicename); 

     ParseRelation relation = object.getRelation("practicerelation"); 


     relation.getQuery().findInBackground(new FindCallback() { 
      @Override 
      public void done(List list, ParseException e) { 
       if (e !=null) { 
        //error 

       } 

       else { 


       } 
      } 


     }); 



     /*mAddGoal = (ImageButton) view.findViewById(R.id.addgoal); 
     mAddGoal.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent = new Intent(parent.getContext(), AddGoal.class); 
       v.getContext().startActivity(intent); 
      } 


     });*/ 

     return view; 
+0

Как о показе цели, и при нажатии открыть новую активность/фрагмент, чтобы показать данные отношения? – cYrixmorten

+0

@cYrixmorten на предыдущем экране Я показываю цели; это подробный вид, показывающий больше информации о них –

+0

Но выбор отношений для каждой цели кажется неэффективным, я бы подумал, что вы хотите показать отношения только для одной выбранной цели. В любом случае ... 'отношение.getQuery(). FindInBackground' - это асинхронный вызов, поэтому он должен происходить где-то в другом месте, кроме' getItemView', так как когда 'getItemView' возвращает отображаемое представление,' findInBackground' еще не завершено. – cYrixmorten

ответ

1

Хорошо, теперь, когда я понимаю вашу ситуацию, я готов придумать ответ.

Что вам нужно сделать (по крайней мере, по моему мнению), это изменить ваше отношение к массиву указателей. До тех пор, пока вы не храните не более 100 точек указателей, в этом дизайне не должно быть заметных проблем с производительностью.

Огромное преимущество наличия массива указателей на отношения состоит в том, что они могут быть включены непосредственно в запрос.

Теперь вы можете сделать что-то вроде этого:

public class GoalDetailViewAdapter extends ParseQueryAdapter<ParseObject> { 

    protected ParseObject mPracticeName; 



    public GoalDetailViewAdapter(Context context) { 




     super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() { 

      public ParseQuery create() { 
       // Here we can configure a ParseQuery to display 
       // midwives 
       ParseQuery<ParseObject> query = ParseQuery.getQuery("goal"); 
       query.whereEqualTo("createdby", ParseUser.getCurrentUser()); 

       // now all the pointers will be populated with data 
       // once the query returns 
       query.include("practicerelation"); 

       return query; 
      } 
     }); 
    } 



    @Override 
    public View getItemView(ParseObject object, View view, final ViewGroup parent) { 

     if (view == null) { 
      view = View.inflate(getContext(), R.layout.activity_goal_detail_view, null); 

     } 

     //use midwifefirm as item view/list 

     super.getItemView(object, view, parent); 


     // find in layout the practice name 
     TextView titleTextView = (TextView) view.findViewById(R.id.goalname); 

     //in the midwifefirm data model, call getPracticename 
     titleTextView.setText(object.getString("goalname")); 


     TextView practiceTextView = (TextView) view.findViewById(R.id.practicename); 

     // now you can iterate the practices directly 
     // note that this is not async no more   
     List<ParseObject> practices = object.getList("practicerelation") 

     StringBuilder b = new StringBuilder(); 
     for (ParseObject practice: practices) { 
      // assuming you have a 'step' col 
      // this is just for the sake of example 
      String step = practice.getString("step"); 
      b.append(step); 
      b.append(","); 
     } 

     practiceTextView.setText(b.toString()); 

     return view; 
1

Это может быть не лучший способ сделать это, но особенно учитывая FindInBackground быть Async и выполнения синхронизированного Find, которая может замедлить ваш пользовательский интерфейс я мог бы предложить следующее

@Override 
public View getItemView(ParseObject object, View view, final ViewGroup parent) { 

    if (view == null) { 
     view = View.inflate(getContext(), R.layout.activity_goal_detail_view, null); 

    } 

    //use midwifefirm as item view/list 

    super.getItemView(object, view, parent); 


    // find in layout the practice name 
    TextView titleTextView = (TextView) view.findViewById(R.id.goalname); 

    //in the midwifefirm data model, call getPracticename 
    titleTextView.setText(object.getString("goalname")); 


    TextView practiceTextView = (TextView) view.findViewById(R.id.practicename); 

    mShowGoal= (ImageButton) view.findViewById(R.id.showgoal); 
    mShowGoal.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(parent.getContext(), ShowGoal.class); 
      intent.put("goalId", object.getObjectId()); 
      v.getContext().startActivity(intent); 
     } 


    }); 

    /*mAddGoal = (ImageButton) view.findViewById(R.id.addgoal); 
    mAddGoal.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(parent.getContext(), AddGoal.class); 
      v.getContext().startActivity(intent); 
     } 


    });*/ 

    return view; 
} 

Так каждый itemview будет иметь кнопку (или может быть все, что вы могли бы подключить onclicklistener), которая запустит новый фрагмент/действие, и вы можете передать все, связывая свою цель с ее конкретными данными.

В зависимости от того, как хранятся ваши данные, нужно что-то передать lse, а не objectId.

public class ShowGoal extends FragmentActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 


    Intent i = getIntent(); 
    String goalId = i.getString("goalId"); 
    ParseQuery query = new ParseQuery("extrainfo"); 
    query.whereEqualTo("pointer_column", goalId); 
    query.findInBackground(new FindCallback<ParseObject>() { 
    public void done(List<ParseObject> scoreList, ParseException e) { 
     if (e == null) { 
      //Success! 
     } else { 
      //Failed 
     } 
    }); 
} 

Надеюсь, это поможет! Cheers

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