listview活动中出现意外错误

时间:2013-11-22 19:01:55

标签: android listview asynchronous

我已经这样做了大约一个星期了,我一直在尝试通过PHP从mySQL填充数据的方法很多。我看过一个教程并试图使用它。它没有错误,但问题是它在我的listview活动中没有显示任何内容。我使用了不同的方法,并在登录后知道我的应用程序已关闭。

这是我的代码:

SubjectsActivity.java:

package com.example.taxamsp;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.example.taxamsp.extra.alertManager;
import com.example.taxamsp.extra.connectionDetector;
import com.example.taxamsp.extra.JSONParser;

public class SubjectsActivity extends ListActivity {
// Connection detector
connectionDetector cd;

// Alert dialog manager
alertManager alert = new alertManager();

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> subjectslist;

// albums JSONArray
JSONArray subjects = null;

// albums JSON url
private static final String URL_SUBJECTS = "http://192.168.43.100/tx/getsubject.php";

// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_FULLNAME = "fullname";
private static final String TAG_IDNUMBER = "idnumber";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.subjects);

    cd = new connectionDetector(getApplicationContext());

    // Check for internet connection
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(SubjectsActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Hashmap for ListView
    subjectslist = new ArrayList<HashMap<String, String>>();

    // Loading subjects JSON in Background Thread
    new loadsubjects().execute();

    // get listview
    ListView lv = getListView();     
}

/**
 * Background Async Task to Load all Subjects by making http request
 * */
class loadsubjects extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(SubjectsActivity.this);
        pDialog.setMessage("Populating Subjects ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Albums JSON
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // getting JSON string from URL
        String json = jsonParser.makeHttpRequest(URL_SUBJECTS, "GET",
                params);

        // Check your log cat for JSON reponse
        Log.d("Subjects JSON: ", "> " + json);

        try {               
            subjects = new JSONArray(json);

            if (subjects != null) {
                // looping through All albums
                for (int i = 0; i < subjects.length(); i++) {
                    JSONObject c = subjects.getJSONObject(i);

                    // Storing each json item values in variable
                    String id = c.getString(TAG_ID);
                    String fullname = c.getString(TAG_FULLNAME);
                    String idnumber = c.getString(TAG_IDNUMBER);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_FULLNAME, fullname);
                    map.put(TAG_IDNUMBER, idnumber);

                    // adding HashList to ArrayList
                    subjectslist.add(map);
                }
            }else{
                Log.d("Albums: ", "null");
            }

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

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all albums
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        SubjectsActivity.this, subjectslist,
                        R.layout.s_content, new String[] { TAG_ID,
                                TAG_FULLNAME, TAG_IDNUMBER }, new int[] {
                                R.id.subject_id, R.id.courseName, R.id.courseCode });

                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
}

alertManager.java:

package com.example.taxamsp.extra;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

import com.example.taxamsp.R;

public class alertManager {
/**
 * Function to display simple Alert Dialog
 * @param context - application context
 * @param title - alert dialog title
 * @param message - alert message
 * @param status - success/failure (used to set icon)
 *               - pass null if you don't want icon
 * */
public void showAlertDialog(Context context, String title, String message,
        Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    if(status != null)
    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.show();
}
}

connectionDetector.java

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class connectionDetector {

private Context _context;

public connectionDetector(Context context){
    this._context = context;
}

/**
 * Checking for all possible internet providers
 * **/
public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}
}

JSONParser.java:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

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
public String makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // 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());
    }

    // return JSON String
    return json;

}
}

subjects.xml

<?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:background="#0099cc"
android:orientation="horizontal" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@android:id/list"
        android:layout_width="321dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="0.54"
        android:text="@string/availSub"
        android:textColor="@android:color/white"
        android:textSize="30sp" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="647dp"
        android:layout_marginTop="20dp"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp"
        android:cacheColorHint="#00000000" >
    </ListView>

    <Button
        android:id="@+id/logoutButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="120dp"
        android:layout_weight="0.54"
        android:background="@android:color/darker_gray"
        android:text="@string/Logout"
        android:textColor="@android:color/white"
        android:textColorLink="@android:color/white" />

</LinearLayout>
</LinearLayout>

s_content.xml:

<?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/subject_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone" />

 <TextView
    android:id="@+id/courseCode"
    android:paddingLeft="2dp"
    android:textSize="20dp"
    android:textStyle="bold"
    android:textColor="#0000FF"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/courseName"
    android:paddingLeft="5dp"
    android:textColor="#5C002E"
    android:textSize="17dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

logcat的:

11-23 02:26:31.263: D/json(918): {"password":"r","username":"r"}
11-23 02:26:31.293: D/URL(918): http://192.168.43.100/tx/login.php
11-23 02:26:33.123: D/Result(918): ok
11-23 02:26:33.333: D/dalvikvm(918): GC_CONCURRENT freed 447K, 8% free 6485K/6983K, paused 75ms+92ms, total 291ms
11-23 02:26:33.373: D/AndroidRuntime(918): Shutting down VM
11-23 02:26:33.373: W/dalvikvm(918): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-23 02:26:33.403: E/AndroidRuntime(918): FATAL EXCEPTION: main
11-23 02:26:33.403: E/AndroidRuntime(918): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.taxamsp/com.example.taxamsp.SubjectsActivity}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ListView
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.os.Looper.loop(Looper.java:137)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.ActivityThread.main(ActivityThread.java:4745)
11-23 02:26:33.403: E/AndroidRuntime(918):  at java.lang.reflect.Method.invokeNative(Native Method)
11-23 02:26:33.403: E/AndroidRuntime(918):  at java.lang.reflect.Method.invoke(Method.java:511)
11-23 02:26:33.403: E/AndroidRuntime(918):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-23 02:26:33.403: E/AndroidRuntime(918):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-23 02:26:33.403: E/AndroidRuntime(918):  at dalvik.system.NativeStart.main(Native Method)
11-23 02:26:33.403: E/AndroidRuntime(918): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ListView
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.ListActivity.onContentChanged(ListActivity.java:241)
11-23 02:26:33.403: E/AndroidRuntime(918):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:259)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.Activity.setContentView(Activity.java:1867)
11-23 02:26:33.403: E/AndroidRuntime(918):  at com.example.taxamsp.SubjectsActivity.onCreate(SubjectsActivity.java:59)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.Activity.performCreate(Activity.java:5008)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-23 02:26:33.403: E/AndroidRuntime(918):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
11-23 02:26:33.403: E/AndroidRuntime(918):  ... 11 more

这是阻止进步的唯一因素。我需要你的帮助!拜托,我真的不知道该怎么办。抱歉这个愚蠢的帖子。我在android中有点新手。

1 个答案:

答案 0 :(得分:1)

在subjects.xml布局文件中

<TextView
    android:id="@android:id/list"
    android:layout_width="321dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_weight="0.54"
    android:text="@string/availSub"
    android:textColor="@android:color/white"
    android:textSize="30sp" />

<ListView
    android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="647dp"
    android:layout_marginTop="20dp"
    android:divider="#b5b5b5"
    android:dividerHeight="1dp"
    android:cacheColorHint="#00000000" >
</ListView>

你不应该给TextView id android:id =“@ android:id / list”因为它是为listview保留的。您看到的错误是,系统正在尝试将TextView转换为ListView,因为您通过执行以下操作告诉textview是listview:android:id =“@ android:id / list”。