Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6827603
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T22:17:05+00:00 2026-05-26T22:17:05+00:00

I have this following method that connectss to db and returns a json array.

  • 0

I have this following method that connectss to db and returns a json array.

private String getServerData(String returnString) {

       InputStream is = null;

       String result = "";
        //the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year","1970"));

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(KEY_121);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }

        //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }

        try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                   // JSONObject json_data = jArray.getJSONObject(i);
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag","id: "+json_data.getInt("id")+
                            ", name: "+json_data.getString("name")+
                            ", sex: "+json_data.getInt("sex")+
                            ", birthyear: "+json_data.getInt("birthyear")
                    );


                        //Get an output to the screen
                        returnString += "\n\t" + jArray.getJSONObject(i); 
                }
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());

                returnString += result.toString();
        }
        return returnString; 
    }   

I then want to call this method from outside but being very new to java I am not sure how to get that sting in put it in hm object like the one thats commented out. See the code below

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView listView = (ListView)findViewById(R.id.list);
        myBooks = new ArrayList<HashMap<String,Object>>();
        HashMap<String, Object> hm;
        hm = new HashMap<String, Object>();
        List<String> list=new ArrayList<String>();
        list.add(getServerData(KEY_121));





        //With the help of HashMap add Key, Values of Book, like name,price and icon path 
       /* hm = new HashMap<String, Object>();
        hm.put(BOOKKEY, "Android");
        hm.put(PRICEKEY, "Price Rs: 500");
        hm.put(IMGKEY, R.raw.android); //i have images in res/raw folder

        myBooks.add(hm);


 SimpleAdapter adapter = new SimpleAdapter(this, myBooks, R.layout.listbox, 
                new String[]{BOOKKEY,PRICEKEY,IMGKEY}, new int[]{R.id.text1, R.id.text2, R.id.img});

        listView.setAdapter(adapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 
    }

My object here is to get the returning string and add it to the myBooks object by using hm object just like how its done in the commented code.

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T22:17:06+00:00Added an answer on May 26, 2026 at 10:17 pm

    Since getServerData() is going to take a while to execute (it contains an http request), you cannot run it directly from the UI thread. (onCreate() is directly on the UI thread, and the UI thread should never be paused).

    This means you have to create an AsyncTask and call getServerData() from the doInBackground() of your AsyncTask. You can return the display JSON result in the AsyncTask‘s onPostExecute().

    This means that you want to pass a SoftReference of where you want to show your result to the AsyncTask. You want to make it a SoftReference in case something happens while you’re fetching the JSON (like you navigate away from the Activity).

    I would suggest that you read this Android blog article and create your own project with the code from the article. Once you have that up and running, modify the that image downloader to a JSON downloader. The article should be really helpful to you, since it also uses an Adapter to show items in a List View.

    Your example is different from the one in the article in several ways, but I think it’s actually simpler, so if you get your head wrapped around the code in the article, then you’ll be able to get your code working afterward.

    References:
    AsyncTask
    SoftReferences
    Multithreading for Performance
    Working Code from the Article Above which implements something like you want but w images

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is with C# and .net 3.5 Let's say I have the following method:
can someone please show me documentation on this method? i have the following line:
I have this following setup, a textarea named with some data in it that
I have this Regular Expression that matches the following strings: <!-- 09-02-2009 ---> <!--
I have this following IEnumerable LINQ query: var query = from p in Enumerable.Range(2,
I have following this blog in setting Xvfb in my ubuntu environment: http://corpocrat.com/2008/08/19/how-to-install-xvfb-x11-server-in-linux-server/ So
Never thought I'd have this problem :) The following snippet of code works in
Let's say we have following this: <p class=first>This is paragraph 1.</p> <p class=second>This is
I have this timer function, it gives me following exception. Collection was modified; enumeration
I have this .NET regex: ^(?<prefix>([^]*))\s(?<attrgroup>(\([^\)]*\)))\s(?<suffix>([^]*))$ It properly matches the following strings: some prefix

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.