-3

I have an android code which i am sharing below. in the ninth step i.e step 9 can the input stream be converted into json before the result is displayed in the last step. If yes how? . please help i just want the result should be what i get from the url. i am getting result as an Xml till now

public class MainActivity extends Activity implements OnClickListener {

TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;

Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // get reference to the views
    tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
    etName = (EditText) findViewById(R.id.etName);
    etCountry = (EditText) findViewById(R.id.etCountry);
    //etTwitter = (EditText) findViewById(R.id.etTwitter);
    btnPost = (Button) findViewById(R.id.btnPost);

    // check if you are connected or not
    if(isConnected()){
        tvIsConnected.setBackgroundColor(0xFF00CC00);
        tvIsConnected.setText("You are conncted");
    }
    else{
        tvIsConnected.setText("You are NOT conncted");
    }

    // add click listener to Button "POST"
    btnPost.setOnClickListener(this);

}

public static String POST(String url, Person person){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("Email", person.getName());
        jsonObject.accumulate("pass", person.getCountry());
        //jsonObject.accumulate("twitter", person.getTwitter());

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person); 

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();


        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

public boolean isConnected(){
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) 
            return true;
        else
            return false;    
}
@Override
public void onClick(View view) {

    switch(view.getId()){
        case R.id.btnPost:
            if(!validate())
                Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
            // call AsynTask to perform network operation on separate thread
            new HttpAsyncTask().execute("http://dev.myurl");
        break;
    }

}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        person = new Person();
        person.setName(etName.getText().toString());
        person.setCountry(etCountry.getText().toString());
        //person.setTwitter(etTwitter.getText().toString());

        return POST(urls[0],person);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
   }
}

private boolean validate(){
    if(etName.getText().toString().trim().equals(""))
        return false;
    else if(etCountry.getText().toString().trim().equals(""))
        return false;
    //else if(etTwitter.getText().toString().trim().equals(""))
    //return false;

    else
        return true;    
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}   
}
user3305582
  • 29
  • 3
  • 9
  • http://stackoverflow.com/questions/21480634/unable-to-loop-through-dynamic-json-string-recursively-in-android/21480997#21480997 – Pararth Feb 13 '14 at 11:04

1 Answers1

0
/*Try using Gson library to prepare Json string from your service, sample code is given below    

JsonObject myObj = new JsonObject(); //Create Json Object

myObj.addProperty("Email", person.getName()); //Add properties to your Json object
myObj.addProperty("pass", person.getCountry());

return new Gson().toJson(myObj); //Convert Json Object to String and return from your service*/


HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String resp = null;
JsonObject myObj = null;

if (entity != null) {
    resp = EntityUtils.toString(entity);
    Gson gson = new Gson();

    myObj = gson.fromJson(resp, JsonElement.class).getAsJsonObject();
}
Purushotham
  • 3,770
  • 29
  • 41