【问题标题】:Trying to populate the JSON data into listview尝试将 JSON 数据填充到列表视图中
【发布时间】:2013-08-05 14:23:39
【问题描述】:

我正在尝试学习如何将 JSON 数据填充到 android ListView 中

My JSON URL:: http://54.218.73.244:7000/

  • 我正在尝试从服务器解析数据并获取 JSON 和 解析它以将数据填充到 listView。

  • 难以完成要求的任务

任何想法


ListAdapter.java

public class ListAdapter extends ArrayAdapter<Item> {
    private List<Item> items;
    public ListAdapter(Context context, int resource, List<Item> items) {
        super(context, resource, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        TextView tt = null;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.itemlistrow, null);
            tt = (TextView) v.findViewById(R.id.RestaurantNameID);
        }

        Item p = items.get(position);
        if (p != null) {
            if (tt != null) {
                tt.setText(""+p.getName());
            }

        }
        return v;
    }
}

JSONParser.java

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            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 JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Item.java

public class Item{
    private String Name;

    public Item(String name){
        this.Name = name;
    }
    public String getName(){
        return Name;
    }
}

AndroidJSONParsingActivity.java

public class AndroidJSONParsingActivity extends Activity {

    // url to make request
    private static String url = "http://54.218.73.244:7000/";
    List<Item> yourData = new ArrayList<Item>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONArray json = jParser.getJSONFromUrl(url);

        try {
            for (int i = 0; i < json.length(); i++) {
                JSONObject c = json.getJSONObject(i);

                // Storing each json item in variable
                String NAME=c.getString("restaurantNAME");

                yourData.add(new Item(NAME));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ListView yourListView = (ListView) findViewById(R.id.listViewID);
        ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);
        yourListView.setAdapter(customAdapter);
        yourListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // When clicked, show a toast with the TextView text
                if(position == 0)
                {
                    //code specific to first list item    
                    Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee1.class);
                    startActivity(myIntent);
                }else if(position == 1)
                {
                    Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee2.class);
                    startActivity(myIntent);                    
                }

            }
        });
    }
}

清单

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".AndroidJSONParsingActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".Employee1"
            android:label="@string/app_name" >
        </activity>

        <activity
            android:name=".Employee2"
            android:label="@string/app_name" >
        </activity>

    </application>

Employee1.java

public class Employee1 extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.employee1);

        Button btn1=(Button) findViewById(R.id.button1);

        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent emp1=new Intent(Employee1.this,AndroidJSONParsingActivity.class);
                startActivity(emp1);
            }
        }); 
    }
}

itemlistrow.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_height="wrap_content" android:orientation="vertical"
             android:layout_width="fill_parent">

    <TableRow android:layout_width="fill_parent"
              android:id="@+id/TableRow01"
              android:layout_height="wrap_content">

        <TextView
                android:id="@+id/RestaurantNameID"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="age" android:textStyle="bold"
                android:gravity="left"
                android:layout_weight="1"
                android:typeface="monospace"
                android:height="40sp"/>
    </TableRow>
</TableLayout>

android_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/listViewID"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:layout_gravity="center">
    </ListView>

</LinearLayout>

LogCat 输出

08-05 10:49:33.429: D/AndroidRuntime(449): Shutting down VM
08-05 10:49:33.429: W/dalvikvm(449): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-05 10:49:33.471: E/AndroidRuntime(449): FATAL EXCEPTION: main
08-05 10:49:33.471: E/AndroidRuntime(449): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.coolnet2/com.example.coolnet2.MainActivity}: java.lang.ClassNotFoundException: com.example.coolnet2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.coolnet2-2.apk]
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.os.Looper.loop(Looper.java:123)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.main(ActivityThread.java:3683)
08-05 10:49:33.471: E/AndroidRuntime(449):  at java.lang.reflect.Method.invokeNative(Native Method)
08-05 10:49:33.471: E/AndroidRuntime(449):  at java.lang.reflect.Method.invoke(Method.java:507)
08-05 10:49:33.471: E/AndroidRuntime(449):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-05 10:49:33.471: E/AndroidRuntime(449):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-05 10:49:33.471: E/AndroidRuntime(449):  at dalvik.system.NativeStart.main(Native Method)
08-05 10:49:33.471: E/AndroidRuntime(449): Caused by: java.lang.ClassNotFoundException: com.example.coolnet2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.coolnet2-2.apk]
08-05 10:49:33.471: E/AndroidRuntime(449):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
08-05 10:49:33.471: E/AndroidRuntime(449):  at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
08-05 10:49:33.471: E/AndroidRuntime(449):  at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
08-05 10:49:33.471: E/AndroidRuntime(449):  ... 11 more

谢谢,

【问题讨论】:

  • 检查所有活动类在同一个包中。也就是 manifest 中声明的包名
  • @ sunil & @ Hemant ......请查看更新的清单文件并记录 cat ...我仍然有一些问题
  • xml 文件表示请放入您的 res/layout 文件,然后我会检查实际错误。
  • @Hemant .... 我已经添加了 XML 文件

标签: android json parsing listview


【解决方案1】:

您的项目中是否有您已在清单文件中声明为启动器活动的 MainActivity.java 类文件?

【讨论】:

  • 请查看更新后的清单文件并记录 cat ...我还有一些问题
  • @sky 尝试清理您的项目并再次构建它,然后运行。你的项目中现在有任何 MainActivity 类吗?
  • 我已经清理了项目...... AndroidJSONParsingActivity.java是这个项目中的主类,其中有Oncreate方法
  • @Sky 你今天可以发,但我明天早上可以还给你
  • 请给我你的邮件ID
【解决方案2】:

好像有很多问题:

1) 您没有在 AndroidManifest.xml 中正确声明所有活动 文件。

=> 如果AndroidJSONParsingActivity 是您的主/启动器活动,则在 AndroidManifest.xml 文件中将其声明为启动器活动。

2) 您在主 UI 线程上直接调用 Web API,这将提供 你NetworkOnMainThreadException

=> 要解决此问题,请在 AsyncTask 中覆盖 Web API 和长时间运行的任务。

// getting JSON string from URL   
 JSONArray json = jParser.getJSONFromUrl(url);

将这段代码写在AsyncTaskdoInBackground()方法中

【讨论】:

  • 请查看更新后的清单文件并记录 cat ...我还有一些问题
  • @Sky 您似乎正在从Employee1 启动AndroidJSONParsingActivity 活动,所以我认为Employee1 应该是您的启动器活动。
  • senario ... 是这样的 :: 有列表(餐厅名称列表).....点击它我需要启动一个活动(employee1 等)....嘿可以我把项目文件发给你……如果你不介意的话……我在这个简单的任务上摸不着头脑……
  • 如果你能给我你的邮件 ID .... 我可以分享我的文件 ... 这对我有很大的帮助 Paresh
  • 感谢帕雷什的指导!
猜你喜欢
  • 1970-01-01
  • 2011-09-03
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多