web-dev-qa-db-fra.com

comment afficher les données JSON récupérées dans listview à l'aide de baseadapter

Je suis nouveau sur Android et Java. Récemment, j'ai des problèmes pour afficher les données JSON récupérées dans Listview à l'aide d'un adaptateur de base. Au début, j'ai utilisé ce code

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

   new TheTask().execute();
  }
     class TheTask extends AsyncTask<Void,Void,String>
  {

@Override
protected String doInBackground(Void... params) {
    String str = null;
    try
    {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
      HttpResponse response = httpclient.execute(httppost);
      str =  EntityUtils.toString(response.getEntity());     
    } 
    catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

    return str;

  }



@Override
    protected void onPostExecute(String result) {

    super.onPostExecute(result);

    String response = result.toString();
    try {


        ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray new_array = new JSONArray(response);

        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                stringArray.add(jsonObject.getString("title").toString());


            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }




        ArrayAdapter<String> adapter = new ArrayAdapter<String>   (MainActivity.this,R.layout.test_tuh,stringArray);            
        ListView list= (ListView) findViewById(R.id.listView1);
        list.setAdapter(adapter);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //tv.setText("error2");
    } 


}
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;
}
  }

Ce code affiche les données JSON récupérées avec succès. Mais il n’affiche qu’une seule ligne. J'ai besoin de plus d'une (deux) lignes dans listview. J'ai donc essayé ce code et cela ne fonctionne pas, il affiche un écran vide.

Mon code est ci-dessous,

 class TheTask extends AsyncTask<Void,Void,String>
  {

    @Override
    protected String doInBackground(Void... params) {
    String str = null;
    try
    {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
      HttpResponse response = httpclient.execute(httppost);
      str =  EntityUtils.toString(response.getEntity());     
    } 
    catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

    return str;

  }


@Override
    protected void onPostExecute(String result) {


    // TODO Auto-generated method stub
    super.onPostExecute(result);

    String response = result.toString();
    try {
         arrayList=new ArrayList<get_set>();

        ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray new_array = new JSONArray(response);



        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                stringArray.add(jsonObject.getString("title").toString());


            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }



   ListView listView;
    adap= new BaseAdapter() {
        LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        @Override
        public View getView(int position, View view, ViewGroup viewgroup) {
            if (view==null) {
                view=inflater.inflate(R.layout.bsdi, null);
            }
            TextView title_tuh=(TextView) view.findViewById(R.id.title1);
            TextView notice_tuh=(TextView) view.findViewById(R.id.notice1);


            title_tuh.setText(arrayList.get(position).getTitle());
            notice_tuh=.setText(arrayList.get(position).getNotice());
            return view;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return arrayList.get(position);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return arrayList.size();
        }
    };


    listView=(ListView) findViewById(R.id.listView1);
    listView.setAdapter(adap);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //tv.setText("error2");
    } 


}

Pour autant que je m'en rende compte, le problème est ici

ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray new_array = new JSONArray(response);



        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                stringArray.add(jsonObject.getString("title").toString());


            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

Pour autant que je sache, les données JSON extraites sont stockées dans stringArray mais ne sont pas utilisées plus tard. Si j'essaye de l'utiliser comme ça, j'obtiens une erreur

title_tuh.setText(stringArray .get(position).getTitle());
notice_tuh=.setText(stringArray .get(position).getNotice());

Si j'essaie de ne pas utiliser ArrayList stringArray = new ArrayList ();

et utilise
arrayList = new ArrayList (); au lieu de cela, alors, je reçois aussi une erreur.

    arrayList=new ArrayList<get_set>();


        JSONArray new_array = new JSONArray(response);


        //JSONArray jsonArray = new JSONArray();
        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                arrayList.add(jsonObject.getString("title").toString());
               // String in = mInflater.inflate(R.layout.custom_row_view, null);

            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

Je ne peux pas trouver comment résoudre ce problème. J'ai vu de nombreux tutoriels en ligne, mais ceux-ci ne m'ont pas été utiles. Aidez-moi, s'il vous plaît.

4
Mushfiqul Tuhin

Vous devez d’abord créer un fichier row_listitem.xml comme:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="fill_parent"
Android:layout_height="80dp"
Android:background="@drawable/list_selector"
Android:orientation="vertical"
Android:padding="5dp" >

<ImageView
    Android:id="@+id/iv_icon_social"
    Android:layout_width="60dp"
    Android:layout_height="60dp"
    Android:layout_centerVertical="true"
    Android:background="@drawable/image_border"
    Android:src="@drawable/sms_t"
    Android:visibility="gone" />

<LinearLayout
    Android:id="@+id/thumbnail"
    Android:layout_width="fill_parent"
    Android:layout_height="85dp"
    Android:layout_marginRight="50dp"
    Android:layout_marginTop="0dp"
    Android:layout_toRightOf="@+id/iv_icon_social"
    Android:gravity="center_vertical"
    Android:orientation="vertical"
    Android:padding="5dip"
    Android:visibility="visible" >

    <TextView
        Android:id="@+id/txt_ttlsm_row"
        Android:layout_width="fill_parent"
        Android:layout_height="wrap_content"
        Android:paddingLeft="10dp"
        Android:text="Sample text"
        Android:textSize="18dp"
        Android:textStyle="bold" />

    <TextView
        Android:id="@+id/txt_ttlcontact_row2"
        Android:layout_width="fill_parent"
        Android:layout_height="wrap_content"
        Android:layout_marginBottom="0dp"
        Android:layout_marginTop="3dp"
        Android:paddingLeft="10dp"
        Android:maxEms="20"
        Android:maxLines="2"
        Android:singleLine="false"
        Android:ellipsize="end"
        Android:text="Sample text2"
        Android:textColor="#808080"
        Android:textSize="15dp"
        Android:textStyle="normal"
        Android:visibility="visible" />


</LinearLayout>

</RelativeLayout>

Maintenant, vous devez créer Custom BaseAdapter like:

  public class BaseAdapter2 extends BaseAdapter {

private Activity activity;
// private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data;
private static ArrayList title,notice;
private static LayoutInflater inflater = null;

public BaseAdapter2(Activity a, ArrayList b, ArrayList bod) {
    activity = a;
    this.title = b;
    this.notice=bod;

    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public int getCount() {
    return title.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.row_listitem, null);

    TextView title2 = (TextView) vi.findViewById(R.id.txt_ttlsm_row); // title
    String song = title.get(position).toString();
    title2.setText(song);


    TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2); // notice
    String song2 = notice.get(position).toString();
    title22.setText(song2);

return vi;

}

}

Maintenant, vous pouvez configurer votre activité principale like:

public class MainActivity extends Activity {

ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();
ListView list;
BaseAdapter2 adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView1);
    new TheTask().execute();
}

class TheTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String str = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://10.0.2.2/BSDI/show.php");
            HttpResponse response = httpclient.execute(httppost);
            str = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return str;

    }



@Override
protected void onPostExecute(String result) {

    super.onPostExecute(result);

    String response = result.toString();
    try {


        JSONArray new_array = new JSONArray(response);

        for (int i = 0, count = new_array.length(); i < count; i++) {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                title_array.add(jsonObject.getString("title").toString());
                notice_array.add(jsonObject.getString("notice").toString());

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        adapter = new BaseAdapter2(MainActivity.this, title_array, notice_array);
        list.setAdapter(adapter);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        // tv.setText("error2");
    }

}
}

 }
9
M D

@ Allen Chun, ce n'est pas dans mon esprit que ce que j'ai modifié dans mon code pour exécuter mon code à la perfection. Mais je partage tous mes codes qui fonctionnent parfaitement.

C'est mon code de mise en page,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical" >

<TextView
    Android:id="@+id/fsr"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:gravity="center"
    Android:text="Notice Board"
    Android:textSize="20px" />

   <TextView
    Android:id="@+id/err_msg"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:text=""
    Android:gravity="center" />

<ListView
    Android:layout_width="wrap_content"
    Android:layout_height="match_parent" 

    Android:id="@+id/list_notice2"

    Android:layout_gravity="center" />




</LinearLayout>

Ceci est mes codes de mise en page personnalisés listview,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical" >

<TextView
    Android:id="@+id/title"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:text="TextView" 
    Android:paddingTop="10dp"
    Android:layout_gravity="center"
      Android:textAppearance="?android:attr/textAppearanceMedium" />
    />

<TextView
    Android:id="@+id/notice"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:text="Small Text"
    Android:paddingTop="5dp"
    Android:layout_gravity="center"
    Android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>

c'est mon activité nommée "NoticeBoard".

public class NoticeBoard extends Activity {


ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();

ListView list;
base_adapter3 adapter;
 TextView f,msg;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_notice);
    list = (ListView) findViewById(R.id.list_notice2);
    msg=(TextView) findViewById(R.id.err_msg);
    new test_ays().execute();
}




class test_ays extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String str = null ;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");

            HttpResponse response = httpclient.execute(httppost);
            str = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();



        }
        return str;


    }



@Override
protected void onPostExecute(String result) {

    super.onPostExecute(result);
    if(result!=null) // add this
    {  
     String response = result.toString();


   try {

        JSONArray new_array = new JSONArray(response);

        for (int i = 0, count = new_array.length(); i < count; i++) {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                title_array.add(jsonObject.getString("title").toString());
                notice_array.add(jsonObject.getString("notice").toString());

            } catch (JSONException e) {
                e.printStackTrace();

            }
        }

        adapter = new base_adapter3(NoticeBoard.this, title_array, notice_array);
      list.setAdapter(adapter);
       // f=(TextView) findViewById(R.id.textTuh);
       // f.setText(title_array);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
       e.printStackTrace();

        // tv.setText("error2");
    }
    }

    else{
        msg.setText("You need a working data connection...");
    }


}
}

}

Et ses codes de base personnalisés,

public class base_adapter2 extends BaseAdapter {


    private Activity activity;
    //private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data;
    private static ArrayList title,notice;
    private static LayoutInflater inflater = null;

    public base_adapter2(Activity a, ArrayList b) {
      activity = a;
      this.title = b;
     // this.notice=bod;

      inflater = (LayoutInflater) activity
              .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public int getCount() {
      return title.size();
    }

    public Object getItem(int position) {
      return position;
    }

    public long getItemId(int position) {
      return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
      View vi = convertView;
      if (convertView == null)
          vi = inflater.inflate(R.layout.bsdi_adapter, null);


      TextView title2 = (TextView) vi.findViewById(R.id.txt1); // title
      String song = title.get(position).toString();
      title2.setText(song);



    return vi;

    }

}
2
Mushfiqul Tuhin

Dans cet exemple, je me connecte à l'URL JSON de la timeline publique de Twitters.

package net.inchoo.demo.andy1;

import Java.io.BufferedReader;
import Java.io.IOException;
import Java.io.InputStreamReader;
import Java.net.MalformedURLException;
import Java.net.URL;
import Java.net.URLConnection;
import Java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Android.app.ListActivity;
import Android.os.Bundle;
import Android.widget.ArrayAdapter;

public class HomeActivity extends ListActivity {

    /** Called when the activity is first created. */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setListAdapter(new ArrayAdapter(this, Android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));        
    }

    public ArrayList<String> fetchTwitterPublicTimeline()
    {
        ArrayList<String> listItems = new ArrayList<String>();

        try {
            URL Twitter = new URL(
                    "http://Twitter.com/statuses/public_timeline.json");
            URLConnection tc = Twitter.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    tc.getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);

                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    listItems.add(jo.getString("text"));
                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return listItems;
    }
}

Veuillez diriger votre attention sur le listItems.add (jo.getString («text»)); ligne. C'est la partie que je suis en train de récupérer un attribut/propriété “text” d'un seul objet JSON. Pour obtenir une image plus «visuelle» de tous les attributs/propriétés disponibles, jetez un œil à la version XML de la chronologie publique de twitters. De cette façon, vous aurez Nice coloré XML dans votre navigateur, où vous pouvez voir tous les attributs disponibles.

Lien: http://inchoo.net/dev-talk/Android-development/simple-Android-json-parsing-example-with-output-into-listactivity/

1
Shubham

ListView à partir deJSONdonnées extraites à l'aide de Retrofit2 service

Réponse JSON

{
  "results": [
    {
      "phone": "+9178XXXX66",
      "name": "Olivia"
    },
    {
      "phone": "+9178XXXX66",
      "name": "Isla"
    },
    {
      "phone": "+9178XXXX66",
      "name": "Emily"
    },
    {
      "phone": "+9178XXXX66",
      "name": "Amelia"
    },
    {
      "phone": "+9178XXXX66",
      "name": "Sophia"
    }],
  "statusCode": "1",
  "count": "2"
}

 enter image description here

Dans MainActivity.Java nous allons transmettre les données JSON sous la forme ArrayList ( dummyData )

    customListAdapter = new CustomListAdapter(getApplicationContext(), dummyData);
    listView = (ListView) findViewById(R.id.listShowJSONData);
    listView.setAdapter(customListAdapter);

En custom BaseAdapter notre

...
...
@Override
public MyModel getItem(int i) {
    return this.users.get(i);
}

@Override
public long getItemId(int i) {
    return i;
}


@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    if(view==null)
    {
        view= LayoutInflater.from(c).inflate(R.layout.json_data_list,viewGroup,false);
    }

    TextView mUserDetails = (TextView) view.findViewById(R.id.userDetails);
    TextView mUserStatus = (TextView) view.findViewById(R.id.userStatus);


    Object getrow = this.users.get(i);
    LinkedTreeMap<Object,Object> rowmap = (LinkedTreeMap) getrow;
    String name = rowmap.get("name").toString();
    String phone = rowmap.get("phone").toString();

    mUserDetails.setText(name);
    mUserStatus.setText(phone);

    return view;
}
...
...

Here MyModel sera utilisé comme modèle de réponse personnalisé que nous obtiendrons du service.

Voir link pour une explication complète du code

0
Code Spy

Obtenir le calendrier

public class GetSchedule extends Activity {

    // JSON Node Names
    private static final String TAG_SNO = "sno";
    private static final String TAG_STNCODE = "stnCode";
    private static final String TAG_STATION = "station";
    // private static final String TAG_ROUTENO= "routeNo";
    private static final String TAG_ARRIVALTIME = "arrivalTime";
    private static final String TAG_DEPTIME = "depTime";

    private JSONArray station = null;

    private ListView list;
    //private static String url = "http://railpnrapi.com/api/route/train/";

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

        try {
            ArrayList<HashMap<String, String>> stnNamelist = new    ArrayList<HashMap<String, String>>();

            // Getting JSON Array
            // JSONObject job = new JSONObject();
            //JSONArray jArray = ModuleClass.trainScheduleJSONObject.getJSONArray("stnName");
            JSONObject json_data = null;
            station= ModuleClass.trainScheduleJSONObject.getJSONArray(TAG_STATION);
            for (int i = 0; i < station.length(); i++) {
                json_data = station.getJSONObject(i);

                // JSONObject c = stnName.getJSONObject(0);

                // Storing  JSON item in a Variable

                String sno = json_data.getString(TAG_SNO);
                String stnCode = json_data.getString(TAG_STNCODE);
                // String distance= c.getString(TAG_DISTANCE);
                // String routeNo = c.getString(TAG_ROUTENO);
                String arrivalTime = json_data.getString(TAG_ARRIVALTIME);
                String depTime = json_data.getString(TAG_DEPTIME);
                // String haltTime = c.getString(TAG_HALTTIME);
                // String tday= c.getString(TAG_TDAY);
                // String remark = c.getString(TAG_REMARK);
                // Adding value HashMap key => value
                stnNamelist = new ArrayList<HashMap<String, String>>();

                HashMap<String, String> map = new HashMap<String, String>();
                map.put(TAG_SNO, sno);
                map.put(TAG_STNCODE, stnCode);
                map.put(TAG_DEPTIME, depTime);
                map.put(TAG_ARRIVALTIME, arrivalTime);
                // map.put(TAG_DEPTIME,depTime );

                stnNamelist.add(map);
                list = (ListView) findViewById(R.id.listView1);
                final SimpleAdapter sd;
                sd = new SimpleAdapter(this, stnNamelist, R.layout.activity_get_schedule, 
                        new String[] { TAG_SNO, TAG_STNCODE, TAG_ARRIVALTIME, TAG_DEPTIME },
                        new int[] { R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4});
                list.setAdapter(sd);
                /*
                 * list.setOnItemClickListener(new
                 * AdapterView.OnItemClickListener() {
                 * 
                 * @Override public void onItemClick(AdapterView<?> parent, View
                 * view, int position, long id) { Toast.makeText(
                 * MainActivity.this, "You Clicked at " +
                 * stnNamelist.get(+position).get( "name"), Toast.LENGTH_SHORT)
                 * .show(); } });
                 */
            }
            // Set JSON Data in TextView
            // uid.setText(id);
            // name1.setText(name);
            // email1.setText(email);
        } 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.get_schedule, menu);
        return true;
    }

}
0
Chande Siddhi
            public class JSONParser {

                static InputStream is = null;
                static JSONObject jObj = null;
                static String json = "";

                // constructor
                public JSONParser() {

                }

                // function get json from url
                // by making HTTP POST or GET mehtod
                @SuppressLint("NewApi")
                public JSONObject makeHttpRequest(String url, String method,
                                                  List<NameValuePair> params) {

                    // Making HTTP request
                    try {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                        // check for request method
                        if(method == "POST"){
                            // request method is POST
                            // defaultHttpClient
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            HttpPost httpPost = new HttpPost(url);
                            httpPost.setEntity(new UrlEncodedFormEntity(params));

                            HttpResponse httpResponse = httpClient.execute(httpPost);
                            HttpEntity httpEntity = httpResponse.getEntity();
                            is = httpEntity.getContent();

                        }else if(method == "GET"){
                            // request method is GET
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            String paramString = URLEncodedUtils.format(params, "utf-8");
                            url += "?" + paramString;
                            HttpGet httpGet = new HttpGet(url);

                            HttpResponse httpResponse = httpClient.execute(httpGet);
                            HttpEntity httpEntity = httpResponse.getEntity();
                            is = httpEntity.getContent();
                        }


                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    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();
                        json = sb.toString();
                    } catch (Exception e) {
                        Log.e("Buffer Error", "Error converting result " + e.toString());
                    }

                    // try parse the string to a JSON object
                    try {
                        jObj = new JSONObject(json);
                    } catch (JSONException e) {
                        Log.e("JSON Parser", "Error parsing data " + e.toString());
                    }

                    // return JSON String
                    return jObj;

                }
            }


        <h1>Model</h1>
        public class WorkModel {

            public String getId() {
                return id;
            }

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

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public String getImagename() {
                return imagename;
            }

            public void setImagename(String imagename) {
                this.imagename = imagename;
            }

            String id,name,imagename;

            public WorkModel(String s1,String s2,String s3)
            {
                this.id=s1;
                name=s2;
                imagename=s3;
            }
        }

    <h1>listview fill</h1>
    public class Work_in_process extends Fragment {

        //////////////jsonparser implement
        JSONParser jsonparser=new JSONParser();
        JSONArray json_users=null;
        JSONObject json;
        /////////

        ListView lst;
        ArrayList<WorkModel> data=new ArrayList<WorkModel>();
        WorkAdapter adapter;
        Context con;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_work_in_process, container, false);
                con=this.getActivity();
                lst=(ListView)rootView.findViewById(R.id.work_listview);

                new work_process().execute();

            // Inflate the layout for this fragment
            return rootView;
        }

        class  work_process extends AsyncTask<String,String,String>
        {
            public Dialog pDialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                pDialog = new ProgressDialog(con);
            pDialog.setMessage("Loading... Please wait...");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(true);
            pDialog.show();
            }

            @Override
            protected String doInBackground(String... args) {
                data.clear();
                List<NameValuePair> params = new ArrayList<NameValuePair>();

                json = jsonparser.makeHttpRequest("your url","POST", params);

                try {
                    int success = json.getInt("status");
                    if (success == 0)
                    {
                        return  "kbc";
                    }
                    else
                    {

                        json_users = json.getJSONArray("result");
                        // looping through All Products
                        for (int i = 0; i < json_users.length(); i++) {
                            JSONObject c = json_users.getJSONObject(i);
                            String t1 = c.getString("id");
                            String t2 = c.getString("work_title");
                            String t3 = c.getString("image_path");
                            WorkModel da=new WorkModel(t1,t2,t3);
                            data.add(da);
                        }

                        return "abc";
                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }

                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                pDialog.dismiss();
                if(s.equals("abc"))
                {
                    adapter = new WorkAdapter(con, data);
                    lst.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                }
                else
                {

                }
            }
        }
    }

<h1>Adapter fill listview</h1>
public class WorkAdapter extends BaseAdapter {

    private LayoutInflater inflater1=null;
    private static String string=null;
    ArrayList<WorkModel> data=null;
    Context activity;
    DisplayImageOptions options;
    protected ImageLoader imageLoader = ImageLoader.getInstance();

    public WorkAdapter(Context act,ArrayList<WorkModel> da)
    {
        activity=act;
        data=da;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View vi=convertView;
        if(convertView==null)
        {
            inflater1=(LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            vi=inflater1.inflate(R.layout.list_work,null);
        }

        TextView name;
        ImageView img;
        name=(TextView)vi.findViewById(R.id.list_work_name);
        img= (ImageView)vi.findViewById(R.id.list_work_img);
        WorkModel da=new WorkModel(string,string,string);
        da=data.get(position);

        final String p1,p2,p3;
        p1=da.getId();
        p2=da.getName();
        p3=da.getImagename();

        name.setText(p2);
        imageLoader.init(ImageLoaderConfiguration.createDefault(activity));

        final String imgpath=""+p3;
        options = new DisplayImageOptions.Builder()

                .showImageOnLoading(R.drawable.wp_loading)
                .showImageForEmptyUri(R.drawable.wp_loading)
                .showImageOnFail(R.drawable.wp_loading)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .build();

        imageLoader.displayImage(imgpath, img,options);

        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DisplayImageOptions options;
                final ImageLoader imageLoader = ImageLoader.getInstance();

                final Dialog emailDialog =new Dialog(activity, Android.R.style.Theme_DeviceDefault);
                emailDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

                emailDialog.setCancelable(true);
                emailDialog.setContentView(R.layout.zoom_imge);

                ImageView image = (ImageView) emailDialog.findViewById(R.id.zoom_image_img);
                emailDialog.show();

                final String imgpath=""+p3;
                options = new DisplayImageOptions.Builder()
                        .showImageOnLoading(R.drawable.wp_loading)
                        .showImageForEmptyUri(R.drawable.wp_loading)
                        .showImageOnFail(R.drawable.wp_loading)
                        .cacheInMemory(true)
                        .cacheOnDisk(true)
                        .build();

                imageLoader.displayImage(imgpath, image, options);
            }
        });




        return vi;
    }
}
0
hardip

Json parser:

public class jparser {

static InputStream istream = null;
static JSONObject jObj = null;
//static JSONArray jarray=null;
static String json = "";
//static JSONArray jarray = null;

// constructor
public jparser() {
}

public JSONObject getJFromUrl(String url) {
    // Making HTTP request
    //try {
        // defaultHttpClient
         StringBuilder builder = new StringBuilder();

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        /*HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        istream = httpEntity.getContent();*/
        try{
        HttpResponse response = httpClient.execute(httpPost);

        StatusLine statusLine = response.getStatusLine();

        int statusCode = statusLine.getStatusCode();

         if (statusCode == 400) 
         {
           HttpEntity entity = response.getEntity();

           InputStream content = entity.getContent();

           BufferedReader reader = new BufferedReader(new InputStreamReader(content));

           String line;

           while ((line = reader.readLine()) != null) 
           {
             builder.append(line);
           }
         } 
         else
         {
             Log.e("==>", "Failed to download file");
         }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        istream.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;

   // Parse String to JSON object

     /*try {
            jarray = new JSONArray( builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jarray;

    }*/
    }

}
0
Chande Siddhi