1

I created a restful web service in php using the slim framework. One of the functions returns a dynamically created multidimensional array and encodes it as a JSON array like this

[{  
    "hid":100001,
    "SubTable":"grpsubs",
    "StatTable":"grpstats",
    "uid":2,
    "Status":"G"
},
{  
    "hid":100002,
    "SubTable":"gtmsubs",
    "StatTable":"gtmstats",
    "uid":2,
    "Status":"R"
}]

In my android app I use the loopj framework to get the restful output like this

AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Authorization", key);
client.post("https://mythic-beanbag-106723.appspot.com/v1/mine", params, new AsyncHttpResponseHandler() {
    // When the response returned by REST has Http response code '200'
    @Override
    public void onSuccess(String response) {
        // Hide Progress Dialog
        hospDialog.hide();
        Log.e("Response", response);
        try {

            JSONArray array = new JSONArray(response);
            Log.e("array", String.valueOf(array.length()));

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getApplicationContext(), "Error Occurred [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
            e.printStackTrace();

        }
    }

Using the Advanced REST Client in chrome I can see the JSON however in my app when I try outputting the JSON in the console Log.e("Response", response); it shows up as an empty array []. This code works for my Login function and in php if instead of using a dynamically created array I use a static array like array("abc"=>array("def"=>"ghi"), "jkl"=>array("mno"=>"pqr")) the above code does output the JSON array.

UPDATE:

params

RequestParams params = new RequestParams();
params.put("uid", prefs.getInt("uid", 0));
cmb
  • 95
  • 3
  • 12
  • Do you understand the difference between POST and GET? On REST console are you using POST or GET? Also what is in your params object? – TerNovi Oct 30 '15 at 17:45
  • @TerNovi I am using post in the REST console and in the php code for the function – cmb Oct 30 '15 at 17:52
  • 1
    I was looking through the docs of the API you are using. It doesn't specify anything about using AsyncHttpClient().post() will return the JSON response you are expecting. Try changing it to AsyncHttpClient().get() instead. – TerNovi Oct 30 '15 at 17:56
  • Great! Upvote my comment if you can please! :) – TerNovi Oct 30 '15 at 18:20

1 Answers1

0
    public class MenuTop extends Activity  {

ArrayList<MenuTopJson> actorsList;
ArrayList<String> id = new ArrayList<String>();
ArrayList<String> onvan = new ArrayList<String>();
ArrayList<String> sath = new ArrayList<String>();
ArrayList<String> zir = new ArrayList<String>();


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.menutop);
    //this.setTitle("Int");
     actorsList = new ArrayList<MenuTopJson>();
    new JSONAsyncTask().execute("https://your web");        
}


class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(MenuTop.this);
        dialog.setMessage("Loading, please wait");
        dialog.setTitle("Connecting server");
        dialog.show();
        dialog.setCancelable(false);
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            //------------------>>
            HttpGet httppost = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            // StatusLine stat = response.getStatusLine();
            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);


                JSONObject jsono = new JSONObject(data);
                JSONArray jarray = jsono.getJSONArray("worldpopulation");
                //db.execSQL("DROP TABLE IF EXISTS '" + CountriesDbAdapter.SQLITE_TABLE + "'");




                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject object = jarray.getJSONObject(i);

                    MenuTopJson actor = new MenuTopJson();

                    actor.setId(object.getString("id"));
                    actor.setOnvan(object.getString("onvan"));
                    actor.setSath(object.getString("sath"));
                    actor.setZir(object.getString("zir"));
                  // Log.d("sss",object.getString("onvan").toString());
                    id.add(object.getString("id").toString());
                    onvan.add(object.getString("onvan").toString());
                    sath.add(object.getString("sath").toString());
                    zir.add(object.getString("zir").toString());


                    actorsList.add(actor);
                }

                return true;
            }

            //------------------>>

        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void onPostExecute(Boolean result) {
        dialog.cancel();
        if(result == true)
        {
        //  Onsql();
            //Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
        //  clearApplicationData();

            Log.d("array=",Arrays.toString(actorsList.toArray()));

            final LinearLayout lm = (LinearLayout) findViewById(R.id.dynamically_create_view_element);

            // create the layout params that will be used to define how your
            // button will be displayed
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
          //  params.height=40;
            params.width=200;
            Log.d("array=",String.valueOf(onvan.size()));
            //Create four 
            for(int j=1;j<=onvan.size();j++) 
            {   
                // Create LinearLayout
                LinearLayout ll = new LinearLayout(MenuTop.this);
                ll.setOrientation(LinearLayout.HORIZONTAL);

            /*    // Create TextView
                TextView product = new TextView(this);
                product.setText(" Product"+j+"    ");
                ll.addView(product);

                // Create TextView
                TextView price = new TextView(this);
                price.setText("  $"+j+"     ");
                ll.addView(price);*/

                // Create Button
                final Button btn = new Button(MenuTop.this);
                    // Give button an ID
                    btn.setId(j+1);
                   // btn.setText("Add To Cart");
                  //  btn.setTextAppearance(this,  R.style.btnStyleShakespeare);

                    //btnStyleShakespeare
                    // set the layoutParams on the button
                    btn.setLayoutParams(params);

                    btn.setText(onvan.get(j-1).toString());

                    final int index = j;
                    // Set click listener for button
                    btn.setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {




                            String id_list=id.get(index-1).toString();
                            String onvan_list=onvan.get(index-1).toString();
                            String sath_list=sath.get(index-1).toString();
                            String zir_list=zir.get(index-1).toString();


                            Log.i("TAG", "index :"   + id_list +":"+onvan_list+":"+sath_list+":"+zir_list);

                          /*  Toast.makeText(getApplicationContext(), 
                              "Clicked:" +"index :" + id_list +":"+onvan_list+":"+sath_list+":"+zir_list, 
                                    Toast.LENGTH_SHORT).show();*/



                          Intent intent = new Intent(MenuTop.this, MenuTopZone1.class);
                          intent.putExtra("key1",id_list);
                          intent.putExtra("key2", onvan_list);
                          intent.putExtra("key3", sath_list);
                          intent.putExtra("key4", zir_list);
                          startActivity(intent);
                          finish();

                        }
                    });

                   //Add button to LinearLayout
                    ll.addView(btn);
                   //Add button to LinearLayout defined in XML
                    lm.addView(ll);  
            }


        }else
        {
            //clearApplicationData();
            //
             //SQLiteDatabase.deleteDatabase("World");
            // clearApplicationData();
        }
    }



}

}

in actor class: package com.wingnity.jmajid;

public class Actors {

private String  id;
private String  shdaneshjo;
private String  moavenat;
private String  darkhast;
private String  startdate;
private String  taiid;

// private String reshteh; private String tozih;

public Actors() {
    // TODO Auto-generated constructor stub
}

public Actors(
        String id,
        String shdaneshjo,
        String moavenat,
        String darkhast,
        String startdate,
        String taiid,
        //String reshteh,
        String tozih
        ) {
    super();

    this.id=id;
    this.shdaneshjo=shdaneshjo;
    this.moavenat=moavenat;
    this.darkhast=darkhast;
    this.startdate=startdate;
    this.taiid=taiid;
    //this.reshteh=reshteh;
    this.tozih=tozih;


}


public String getId() {
    return id;
}

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

public String getShdaneshjo() {
    return shdaneshjo;
}

public void setShdaneshjo(String shdaneshjo) {
    this.shdaneshjo = shdaneshjo;
}

public String getMoavenat() {
    return moavenat;
}

public void setMoavenat(String moavenat) {
    this.moavenat = moavenat;
}

public String getDarkhast() {
    return darkhast;
}

public void setDarkhast(String darkhast) {
    this.darkhast = darkhast;
}
public String getStartdate() {
    return startdate;
}

public void setStartdate(String startdate) {
    this.startdate = startdate;
}

public String getTaiid() {
    return taiid;
}

public void setTaiid(String taiid) {
    this.taiid = taiid;
}

public String getTozih() {
    return tozih;
}

public void setTozih(String tozih) {
    this.tozih = tozih;
}

}

sirmagid
  • 1,090
  • 1
  • 16
  • 23