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

  • SEARCH
  • Home
  • 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 4333910
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T10:27:25+00:00 2026-05-21T10:27:25+00:00

I’m having a JSON file which is populated to a listview.First, I’m wondering how

  • 0

I’m having a JSON file which is populated to a listview.First, I’m wondering how to make my list view is clickable and lead to another activity.

The second, I wanna make the list view dynamic. That means, I only need one Activity for the click action on the list I have. And the source of the content (picture,title,description) which is populated to the Activity comes from a JSON file on the web.

For example, I have 13 projects on the list, whenever I click to one of them it goes to ONE activity containing different picture,title,and description depends on the item I click.

I need somebody to improve the codes I provide below.

Projects.java

public class Projects {

    public String title;
    public String keyword;
    public String description;
    public String smallImageUrl;
    public String bigImageUrl;
    public int cost;

    @Override
    public String toString()
    {
        return "Title: "+title+ " Keyword: "+keyword+ " Image: "+smallImageUrl;

    }


}

ProjectsAdapter.java

Public class ProjectsAdapter extends ArrayAdapter<Projects> {

    int resource;
    String response;
    Context context;
    //Initialize adapter
    public ProjectsAdapter(Context context, int resource, List<Projects> items) {
        super(context, resource, items);
        this.resource=resource;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LinearLayout projectView;
        //Get the current alert object
        Projects pro = getItem(position);

        //Inflate the view
        if(convertView==null)
        {
            projectView = new LinearLayout(getContext());
            String inflater = Context.LAYOUT_INFLATER_SERVICE;
            LayoutInflater vi;
            vi = (LayoutInflater)getContext().getSystemService(inflater);
            vi.inflate(resource, projectView, true);
        }
        else
        {
            projectView = (LinearLayout) convertView;
        }

        TextView Title =(TextView)projectView.findViewById(R.id.title);

        try {
              ImageView i = (ImageView)projectView.findViewById(R.id.image);
              Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(pro.smallImageUrl).getContent());
              i.setImageBitmap(bitmap); 
            } catch (MalformedURLException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }


        //Assign the appropriate data from our alert object above
        //Image.setImageDrawable(pro.smallImageUrl);
        Title.setText(pro.title);

        return projectView;
    }

}

Main.java

public class Main extends Activity {
    /** Called when the activity is first created. */
    //ListView that will hold our items references back to main.xml
    ListView lstTest;
    //Array Adapter that will hold our ArrayList and display the items on the ListView
    ProjectsAdapter arrayAdapter;

    //List that will  host our items and allow us to modify that array adapter
    ArrayList<Projects> prjcts=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Initialize ListView
        lstTest= (ListView)findViewById(R.id.lstText);

         //Initialize our ArrayList
        prjcts = new ArrayList<Projects>();
        //Initialize our array adapter notice how it references the listitems.xml layout
        arrayAdapter = new ProjectsAdapter(Main.this, R.layout.listitems,prjcts);

        //Set the above adapter as the adapter of choice for our list
        lstTest.setAdapter(arrayAdapter);

        //Instantiate the Web Service Class with he URL of the web service not that you must pass
        WebService webService = new WebService("http://pre.spendino.de/test/android/projects.json");

        //Pass the parameters if needed , if not then pass dummy one as follows
        Map<String, String> params = new HashMap<String, String>();
        params.put("var", "");

        //Get JSON response from server the "" are where the method name would normally go if needed example
        // webService.webGet("getMoreAllerts", params);
        String response = webService.webGet("", params);

        try
        {
            //Parse Response into our object
            Type collectionType = new TypeToken<ArrayList<Projects>>(){}.getType();

            //JSON expects an list so can't use our ArrayList from the lstart
            List<Projects> lst= new Gson().fromJson(response, collectionType);

            //Now that we have that list lets add it to the ArrayList which will hold our items.
            for(Projects l : lst)
            {
                prjcts.add(l);
            }

            //Since we've modified the arrayList we now need to notify the adapter that
            //its data has changed so that it updates the UI
            arrayAdapter.notifyDataSetChanged();
        }
        catch(Exception e)
        {
            Log.d("Error: ", e.getMessage());
        }


    }

}

WebService.java (I don’t think we need to edit this one)

public class WebService{

    DefaultHttpClient httpClient;
    HttpContext localContext;
    private String ret;

    HttpResponse response1 = null;
    HttpPost httpPost = null;
    HttpGet httpGet = null;
    String webServiceUrl;

    //The serviceName should be the name of the Service you are going to be using.
    public WebService(String serviceName){
        HttpParams myParams = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 10000);
        httpClient = new DefaultHttpClient(myParams);
        localContext = new BasicHttpContext();
        webServiceUrl = serviceName;

    }

    //Use this method to do a HttpPost\WebInvoke on a Web Service
    public String webInvoke(String methodName, Map<String, Object> params) {

        JSONObject jsonObject = new JSONObject();

        for (Map.Entry<String, Object> param : params.entrySet()){
            try {
                jsonObject.put(param.getKey(), param.getValue());
            }
            catch (JSONException e) {
                Log.e("Groshie", "JSONException : "+e);
            }
        }
        return webInvoke(methodName,  jsonObject.toString(), "application/json");
    }

    private String webInvoke(String methodName, String data, String contentType) {
        ret = null;

        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

        httpPost = new HttpPost(webServiceUrl + methodName);
        response1 = null;

        StringEntity tmp = null;       

        //httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
        httpPost.setHeader("Accept",
"text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

        if (contentType != null) {
            httpPost.setHeader("Content-Type", contentType);
        } else {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        }

        try {
            tmp = new StringEntity(data,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.e("Groshie", "HttpUtils : UnsupportedEncodingException : "+e);
        }

        httpPost.setEntity(tmp);

        Log.d("Groshie", webServiceUrl + "?" + data);

        try {
            response1 = httpClient.execute(httpPost,localContext);

            if (response1 != null) {
                ret = EntityUtils.toString(response1.getEntity());
            }
        } catch (Exception e) {
            Log.e("Groshie", "HttpUtils: " + e);
        }

        return ret;
    }

    //Use this method to do a HttpGet/WebGet on the web service
    public String webGet(String methodName, Map<String, String> params) {
        String getUrl = webServiceUrl + methodName;

        int i = 0;
        for (Map.Entry<String, String> param : params.entrySet())
        {
            if(i == 0){
                getUrl += "?";
            }
            else{
                getUrl += "&";
            }

            try {
                getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            i++;
        }

        httpGet = new HttpGet(getUrl);
        Log.e("WebGetURL: ",getUrl);

        try {
            response1 = httpClient.execute(httpGet);
        } catch (Exception e) {
            Log.e("Groshie:", e.getMessage());
        }

        // we assume that the response body contains the error message
        try {
            ret = EntityUtils.toString(response1.getEntity());
        } catch (IOException e) {
            Log.e("Groshie:", e.getMessage());
        }

        return ret;
    }

    public static JSONObject Object(Object o){
        try {
            return new JSONObject(new Gson().toJson(o));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public InputStream getHttpStream(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            response = httpConn.getResponseCode();                

            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception e) {
            throw new IOException("Error connecting");
        } // end try-catch

        return in;
    }

    public void clearCookies() {
        httpClient.getCookieStore().clear();
    }

    public void abort() {
        try {
            if (httpClient != null) {
                System.out.println("Abort.");
                httpPost.abort();
            }
        } catch (Exception e) {
            System.out.println("Your App Name Here" + e);
        }
    }


}

and here’s the JSON file:

[{
    "title": "CARE Deutschland-Luxemburg e.V.",
    "keyword": "CARE",
    "description": "<p><b>Das CARE-Komplett-Paket für Menschen in Not</b",
    "smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1284113658.jpg",
    "bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1284113658.jpg",
    "cost": "5"
},
{
    "title": "Brot für die Welt",
    "keyword": "BROT",
    "description": "<p>„Brot für die Welt“ unterstützt unter der Maßgabe 'Helfen, wo die Not am größten ist' ausgewählte Projekte weltweit.",
    "smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1267454286.jpg",
    "bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1267454286.jpg",
    "cost": "5"
},
{
    "title": "Deutsche AIDS-Stiftung",
    "keyword": "HIV",
    "description": "<p>Die Deutsche AIDS-Stiftung unterstützt mit ihren finanziellen Mitteln seit mehr als 20 Jahren Betroffene, die an HIV und AIDS erkrankt sind.",
    "smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1258365722.jpg",
    "bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1258365722.jpg",
    "cost": "5"
}]

Screenshot of the list view:
enter image description here

If something is not clear, please let me know.
Thank you very much

  • 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-21T10:27:25+00:00Added an answer on May 21, 2026 at 10:27 am

    Use this to implement the click:

    lstTest.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                    @SuppressWarnings("unchecked")
                    Projects p = (Projects ) lstTest.getItemAtPosition(position);                   
    
                    //Do your logic and open up a new Activity.
                }
            });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
We're building an app, our first using Rails 3, and we're having to build
I have just tried to save a simple *.rtf file with some websites and
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I want use html5's new tag to play a wav file (currently only supported
In my XML file chapters tag has more chapter tag.i need to display chapters
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words

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.