2014-01-26 3 views
0

Получать данные из webservice в формате json и хочу отображать результаты в динамических кнопках. I может отображать результаты в текстовом виде, но я хочу сделать это как отображение кода динамического button.my здесьКак создать динамическую кнопку по отношению к результатам webservice

public class MainActivity extends Activity { 
String url = "http://10.0.2.2:80/android_connect/home.php"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    new LongOperation().execute(url); 




} 

private class LongOperation extends AsyncTask<String, Void, Void> { 
    private final HttpClient Client = new DefaultHttpClient(); 
    private String Content; 
    private String Error = null; 
    private ProgressDialog Dialog = new ProgressDialog(MainActivity.this); 
    String data =""; 
    TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed); 
    int sizeData = 0; 

    protected void onPreExecute() { 

     Dialog.setMessage("Please wait.."); 
     Dialog.show(); 

      } 

    // Call after onPreExecute method 
    protected Void doInBackground(String... urls) { 
      /************ Make Post Call To Web Server ***********/ 
     BufferedReader reader=null; 
       // Send data 
      try 
      { 
       // Defined URL where to send data 
       URL url = new URL(urls[0]); 

       // Send POST data request 
       URLConnection conn = url.openConnection(); 
       conn.setDoOutput(true); 
       OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
       wr.write(data); 
       wr.flush(); 
       // Get the server response 
       reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
        // Read Server Response 
       while((line = reader.readLine()) != null) 
        { 
          // Append server response in string 
          sb.append(line + ""); 
        } 

       // Append Server Response To Content String 
       Content = sb.toString(); 
      } 
      catch(Exception ex) 
      { 
       Error = ex.getMessage(); 
      } 
      finally 
      { 
       try 
       { 
          reader.close(); 
       } 
        catch(Exception ex) {} 
      } 

      return null; 
    } 

    protected void onPostExecute(Void unused) { 

     Dialog.dismiss(); 
       if (Error != null) { 
      jsonParsed.setText("Output : "+Error); 

     } else { 

     jsonParsed.setText(Content); 

      String OutputData = ""; 
      JSONObject jsonResponse; 

      try { 

      jsonResponse = new JSONObject(Content); 

      JSONArray jsonMainNode = jsonResponse.optJSONArray("menu"); 

      int lengthJsonArr = jsonMainNode.length(); 
       for(int i=0; i < lengthJsonArr; i++) 
       { 
        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 

        int pId = jsonChildNode.getInt("pid"); 


        String Pid  = jsonChildNode.optString("pid".toString()); 
         String Name  = jsonChildNode.optString("name").toString(); 

        OutputData += "pid : "+ Pid +" "+ "content : "+ Name+" "; 


       } 


       jsonParsed.setText(OutputData); 

      } catch (JSONException e) { 

       e.printStackTrace(); 
      } 


     } 
    } 
} 



@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

}

ответ

0

Это грубый ответ, но это даст вам то, что вы хотите.

Вам необходимо будет добавить кнопки в меню программно.

Я не знаю вашего результата Json, поэтому вам нужно будет обойти это, чтобы добавить больше кнопок.

// Поместите ViewGroup (т.е. LinearLayout) в вашем activity_main.xml с idbtn_container

в postExecute:

 LinearLayout buttonContainer = (LinearLayout) findViewById(R.id.btn_container); 
     Button button = new Button(buttonContainer.getContext()); 
     button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
     button.setText("Json : " + OutputData); 
     buttonContainer.addView(button); 
+0

его worked..thanks много для вашей помощи .. – ammu

+0

я попытался показать эти кнопки в gridview, но не получается, можете ли вы рассказать, как добавить gridview к этим кнопкам ... – ammu

+0

GridView использует адаптер, вам нужен совершенно другой подход – Blundell

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