마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

탭호스트 질문이요!!제발좀봐주세요ㅠ

0 추천

 

탭호스트에

인기순많은순(내림차순)|인기없는순(오름차순) 으로 하려고합니다.

현재 인기만은순 (내림차순으로)탭을 누르면 정렬이 됩니당.

반대로 인기없는순(오름차순)으로 코딩을 하려면 어떠케 해야될지 모르겠습니당..(php는 작업완료)

아래소스는 인기만은순(내림차순으로)정렬 되는 소스입니다.

 

getData(http://웹서버주소/list_data.php); <-- 내림차순php
getData2(http://웹서버주소/list2_data.php); <--오름차순 php
 
public void onTabChanged(String tabId) {
if(tabId.equalsIgnoreCase("Tab1")) {
Toast.makeText(mContext, "인기많은순", Toast.LENGTH_SHORT).show();
}else if(tabId.equalsIgnoreCase("Tab2")){
Toast.makeText(mContext, "인기없는순", Toast.LENGTH_SHORT).show();
}
}
탭리스너를 달고
 
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
//strList = new ArrayList<String>() ;
strList = new ArrayList<>() ;

for(int i=0;i<peoples.length();i++){

JSONObject c = peoples.getJSONObject(i);
String no = c.getString(TAG_NO);
String likes= c.getString(TAG_LIKES);

Log.d("sort",strList+"");


HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NO,no);
persons.put(TAG_NAME,name);
persons.put(TAG_LIKES,likes);
personList.add(persons);
strList.add(personList);
Log.d("str",strList+"");
}

adapter = new SimpleAdapter(

Main_Page.this, personList,
R.layout.list_item,
new String[]{TAG_NAME,TAG_LIKES},
new int[]{ R.id.name,R.id.textlike}
)
{
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();

if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
TextView txtName = (TextView) convertView.findViewById(R.id.name);
final TextView txtlikes = (TextView) convertView.findViewById(R.id.textlike);


Button button = (Button) convertView.findViewById(R.id.like);
//final TextView editlike = (TextView) convertView.findViewById(R.id.textlike);
txtName.setText(personList.get(position).get("name"));
txtlikes.setText(personList.get(position).get("likes"));
test=personList.get(position).get("addCode");

button.setOnClickListener(new View.OnClickListener() {
String mCount = personList.get(position).get(TAG_LIKES);
@Override
public void onClick(View view) {
//txtlikes.setText(String.valueOf(mCount+1));
txtlikes.setText(""+(Integer.parseInt(mCount)+1));

String likes = txtlikes.getText().toString();

String no = null;
no = personList.get(position).get(TAG_NO);

//insertToDatabase(no,likes);
ModifyActivityState(no,likes);
}
});
return convertView;
}
};
listview.setAdapter(adapter);
listview.setTextFilterEnabled(true);
listview.setClickable(true);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getApplicationContext(),position, Toast.LENGTH_LONG).show();
Log.d("포지션",position+"");

intent = new Intent(mContext,Detail_Activity.class);

intent.putExtra("name",personList.get(position).get(TAG_NAME));
intent.putExtra("likes",personList.get(position).get(TAG_LIKES));
startActivity(intent);
Log.d("인텐트",intent+"");
}
});
} catch (JSONException e) {
e.printStackTrace();
}

}
 
public void getData(String url){
class GetDataJSON extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {

String uri = params[0];
Log.d("uri",uri);

BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();

bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}

return sb.toString().trim();

}catch(Exception e){
return null;
}

}

@Override
protected void onPostExecute(String result){
myJSON=result;
// Log.d("result",result);
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute(url);
}
 
신입생 (510 포인트) 님이 2016년 10월 26일 질문
showList()함수랑
getData()함수도  똑같이 하나더생성해야 되는건지도 궁금합니다.

1개의 답변

0 추천

소스가 좀 어지러워서 뭐가 뭔지 눈에 안들어 오지만 한가지는 먼저 들어오네요. 엄청난 이유가 있지 않다면 아래와 같은 코드는 사용하지 마세요. Object Oriented가 전혀 아닙니다. 예를 들어 peson의 유효성을 검사하는 코드를 추가한다고 가정하면 님의 방법으로 하면 코드가 늘어나고 관리하기도 점점 힘들어 집니다.
 

HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NO,no);
persons.put(TAG_NAME,name);
persons.put(TAG_LIKES,likes);
personList.add(persons);
strList.add(personList);

 

이런 형태로 바꾸세요.

public class Person {
   private String no;
   private String name;
   private int likes;
  
   public Person(){}
   public Person(String no, String name, int likes) {
       this.no = no;
       this.name = name;
       this.likes = likes;
   }
   
   //getter, setter 생략
}

ArrayList<Person> persons = new ArrayList<Person();

for (int i=0, n=peoples.length; i<n; i++) { 
     //json parsing 부 생략
     persons.add(new Person(no, name, likes));
}

 

그리고 getData를 호출하는 부분은 onTabChange 메소드에서 처리하셔야 겠네요.

public void onTabChanged(String tabId) {
   if(tabId.equalsIgnoreCase("Tab1")) {
        getData("http://server/list_data.php"); 
    }else if(tabId.equalsIgnoreCase("Tab2")){
        getData("http://server/list2_data.php"); 
    }
}

public void getData(String url) {
   //여기서 서버에 데이터를 데이터를 요청하면 되겠네요.
}

 

spark (224,800 포인트) 님이 2016년 10월 26일 답변
spark님이 2016년 10월 26일 수정
getData(String url) 에는 저위에있는 소스 그대로 써도되지 않아요?
...