简单显示从JSON解析的项目列表

时间:2014-01-01 06:08:40

标签: java android

Q ::我无法显示从JSON解析的元素列表

MainActivity.java

public class MainActivity extends Activity{
    // Declare Variables
        JSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        Adapter adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        static String NAME = "rank";


        String TYPE_FILTER;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.listview_main);

            TYPE_FILTER = getIntent().getExtras().getString("key_title");
            Log.v("---- Value-Start---", TYPE_FILTER);
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);

            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }

        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(MainActivity.this);
                // Set progressdialog title
                //mProgressDialog.setTitle("Fetching the information");
                // Set progressdialog message
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<HashMap<String, String>>();

                // Retrieve JSON Objects from the given URL address
                jsonobject = Parser.getJSONfromURL("http://54.218.73.244:7004/DescriptionSortedPrice/");

                try {
                    // Locate the array name in JSON
                    jsonarray = jsonobject.getJSONArray("restaurants");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put(MainActivity.NAME, jsonobject.getString("Person_Name"));

                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {
                // Pass the results into ListViewAdapter.java
                adapter = new Adapter(MainActivity.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
    }

Adapter.java

public class Adapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public Adapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
    }

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

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

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

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView name;

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

        View itemView = inflater.inflate(R.layout.single_item, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);

        // Capture position and set results to the TextViews
        name.setText(resultp.get(MainActivity.NAME));


        return itemView;
    }
}

Parser.java

public class Parser {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            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 {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

日志 ::

01-01 11:28:44.719: E/AndroidRuntime(566): FATAL EXCEPTION: main
01-01 11:28:44.719: E/AndroidRuntime(566): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.listviewdemo/com.example.listviewdemo.BLD_IndividualListOfItems_Starterss}: java.lang.ClassNotFoundException: com.example.listviewdemo.BLD_IndividualListOfItems_Starterss in loader dalvik.system.PathClassLoader[/data/app/com.example.listviewdemo-2.apk]
01-01 11:28:44.719: E/AndroidRuntime(566):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
01-01 11:28:44.719: E/AndroidRuntime(566):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-01 11:28:44.719: E/AndroidRuntime(566):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-01 11:28:44.719: E/AndroidRuntime(566):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-01 11:28:44.719: E/AndroidRuntime(566):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-01 11:28:44.719: E/AndroidRuntime(566):  at android.os.Looper.loop(Looper.java:123)
01-01 11:28:44.719: E/AndroidRuntime(566):  at android.app.ActivityThread.main(ActivityThread.java:4627)
01-01 11:28:44.719: E/AndroidRuntime(566):  at java.lang.reflect.Method.invokeNative(Native Method)
01-01 11:28:44.719: E/AndroidRuntime(566):  at java.lang.reflect.Method.invoke(Method.java:521)
01-01 11:28:44.719: E/AndroidRuntime(566):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-01 11:28:44.719: E/AndroidRuntime(566):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-01 11:28:44.719: E/AndroidRuntime(566):  at dalvik.system.NativeStart.main(Native Method)
01-01 11:28:44.719: E/AndroidRuntime(566): Caused by: java.lang.ClassNotFoundException: com.example.listviewdemo.BLD_IndividualListOfItems_Starterss in loader dalvik.system.PathClassLoader[/data/app/com.example.listviewdemo-2.apk]
01-01 11:28:44.719: E/AndroidRuntime(566):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
01-01 11:28:44.719: E/AndroidRuntime(566):  at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
01-01 11:28:44.719: E/AndroidRuntime(566):  at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
01-01 11:28:44.719: E/AndroidRuntime(566):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-01 11:28:44.719: E/AndroidRuntime(566):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
01-01 11:28:44.719: E/AndroidRuntime(566):  ... 11 more

2 个答案:

答案 0 :(得分:1)

使用此代码 在服务器端创建setter和getters

我发送reps2,branchname和reps3都是使用get和seters从服务器到客户端,然后使用jason对象解析jason响应。

public class Workshop extends Activity
{
    Boolean isInternetPresent = false;
    InternetConnection cd;
    public EditText uname,pwd;
    public Button btnlog1,btncancel1;
    public boolean connect=false,logged=false;
    public String db_select;
     String mUname;
    ListView l1,l2;
    Spinner s;
    public Iterator<String> itr,itr1;
    private final String SERVICE_URL = "Your URL";
    private final String TAG = "Workshop";
    ArrayList<String> todoItems,cad;
    ArrayAdapter<String> aa,a1;

    public List<String> list1=new ArrayList<String>();
    public List<String> list12=new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        Workshop.this.setContentView(R.layout.workshop);
         l1 = (ListView)findViewById(R.id.listView1);
         l2 = (ListView)findViewById(R.id.listView2);
         todoItems = new ArrayList<String>();
         cad=new ArrayList<String>();
            aa = new ArrayAdapter<String>(this,R.layout.mylist,R.id.list_content,todoItems);
            l1.setAdapter(aa);
            a1 = new ArrayAdapter<String>(this,R.layout.mylist,R.id.list_content,cad);
            l2.setAdapter(a1);

//      
    public void handleResponse(String response) 
    {   // display("JSON responce is : "+response);
        try {

            JSONObject jso = new JSONObject(response);




                  if( UName.equalsIgnoreCase("") || UName==null)
                  {
                     display("Project report(s) can not be retrieved.");
                  }
                  else
                  {
//                     int count=Integer.parseInt(UName);
//                     display("Number of Projects have been handling in AFL right now: "+count);
                    list1=new ArrayList<String>();
                    list12=new ArrayList<String>();
                    JSONArray array=jso.getJSONArray("reps2");
                    JSONArray array1=jso.getJSONArray("reps3");
                    for(int i=0;i<array.length();i++)
                    {
                        list1.add(array.getJSONObject(i).getString("branchName"));
                        list12.add(array1.getJSONObject(i).getString("branchName1"));

                    }
                    itr=list1.iterator();
                    itr1=list12.iterator();
                    while(itr.hasNext()&&itr1.hasNext())
                    {

                        todoItems.add(0, itr.next().toString());
                        cad.add(0, itr1.next().toString());
                        aa.notifyDataSetChanged();
                        a1.notifyDataSetChanged();
                    }




                  }      
        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
            return;
        }

    }

}

答案 1 :(得分:1)

你应该改变这个:

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

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