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

서버내 파일리스트를 spinner로 불러오려합니다.

0 추천
php

    function getPath1List() {
        $dir='00';
        $files = scandir($dir);
        $file_path1 = array();
        $file_path1["categories"] = array();
        
        foreach($files as $ind_file) {
            $tmp = array();
            $tmp["filePath1"] = $ind_file;
            
            array_push($file_path1["categories"], $tmp);
        }
        
        header('Content-Type: application/json');
    
        echo json_encode($file_path1);
    }
    getPath1List();

결과값은

{"categories":[{"filePath1":"."},{"filePath1":".."},{"filePath1":"2016_04_20"},{"filePath1":"2016_04_21"},{"filePath1":"2016_04_22"},{"filePath1":"2016_04_23"},{"filePath1":"2016_04_24"},{"filePath1":"2016_04_25"},{"filePath1":"2016_04_26"}
android에서 데이터값을 받아오기위해서 사용한 util은

get & set 용

public class Category {

    private String filePath1;

    public Category(){}
    public Category(String filePath1) {
        this.filePath1 = filePath1;
    }

    public String getFilePath1() {
        return filePath1;
    }

    public void setFilePath1(String filePath1) {
        this.filePath1 = filePath1;
    }
}

유틸

public class ServiceHandler {

   static InputStream is = null;
   static String file_path1 = null;
   public final static int GET = 1;
   public final static int POST = 2;

   public ServiceHandler() {

   }
   public String makeServiceCall(String url, int method) {
       return this.makeServiceCall(url, method, null);
   }
   public String makeServiceCall(String url, int method,
           List<NameValuePair> params) {
       try {
           // http client
           DefaultHttpClient httpClient = new DefaultHttpClient();
           HttpEntity httpEntity = null;
           HttpResponse httpResponse = null;
            
           // Checking http request method type
           if (method == POST) {
               HttpPost httpPost = new HttpPost(url);
               // adding post params
               if (params != null) {
                   httpPost.setEntity(new UrlEncodedFormEntity(params));
               }

               httpResponse = httpClient.execute(httpPost);

           } else if (method == GET) {
               // appending params to url
               if (params != null) {
                   String paramString = URLEncodedUtils
                           .format(params, "utf-8");
                   url += "?" + paramString;
               }
               HttpGet httpGet = new HttpGet(url);

               httpResponse = httpClient.execute(httpGet);

           }
           httpEntity = httpResponse.getEntity();
           is = httpEntity.getContent();

       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
       } catch (ClientProtocolException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }

       try {
           BufferedReader reader = new BufferedReader(new InputStreamReader(
                   is, "UTF-8"), 8);
           StringBuilder sb = new StringBuilder();
           String line = null;
           while ((line = reader.readLine()) != null) {
               sb.append(line + "\n");
           }
           is.close();
           file_path1 = sb.toString();
       } catch (Exception e) {
           Log.e("Buffer Error", "Error: " + e.toString());
       }

       return file_path1;

   }
}

게시판 제한때문에 나머지부분은 댓글로남기겠습니다.
eorl0533 (160 포인트) 님이 2016년 6월 7일 질문
게시판 글자수 제한때문에 따로남깁니다.

activity 입니다.

public class FileListActivity extends Activity implements OnItemSelectedListener {

    private TextView txtRes;
    private Spinner sp_path1;
    private ArrayList<Category> categoriesList;
    ProgressDialog pDialog;
    
    //값을 가져올 url
    private String url = "php가있는 서버url";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filelist);
        
        //첫번째 루트 spinner
        sp_path1 = (Spinner)findViewById(R.id.spinner);
        txtRes = (TextView)findViewById(R.id.textView2);
        
        categoriesList = new ArrayList<Category>();

        sp_path1.setOnItemSelectedListener(this);
        
        new GetCategories().execute();
    }
    
    private class GetCategories extends AsyncTask<Void, Void, Void> {

        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(FileListActivity.this);
            pDialog.setMessage("리스트를 불러오는중...");
            pDialog.setCancelable(false);
            pDialog.show();
        }
        
        @Override
        protected Void doInBackground(Void... params) {
            ServiceHandler jsonParser = new ServiceHandler();
            String json = jsonParser.makeServiceCall(url, ServiceHandler.GET);
            
            Log.e("Response : ", "> " + json);
            
            if(json != null) {
                try {
                    JSONObject jsonObj = new JSONObject(json);
                    if(jsonObj != null) {
                        JSONArray categories = jsonObj.getJSONArray("categories");
                        
                        for(int i=0; i < categories.length(); i++) {
                            JSONObject catObj = (JSONObject)categories.get(i);
                            Category cat = new Category(catObj.getString("filePath1"));
                            categoriesList.add(cat);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("JSON Data", "서버 연결에 실패하였습니다.");
            }
            return null;
        }
        
        protected void onPostExcute(Void result) {
            super.onPostExecute(result);
            if(pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
        
    }
    
    
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(getApplicationContext(), parent.getItemAtPosition(position).toString() + "Selected", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        
    }
    
}

입니다 dialog만 계속해서 돌면서 리스트를 못불러오네여 ㅠ

도와주세요 ㅠ

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...