简体   繁体   中英

Display ListView when button Click

I'm new to android and I hope someone could help me here. I have an activity Faculty and a button.

This is my XML layout browse_faculty:

<Button
    android:onClick="searchFSTEHandler"
    android:id="@+id/bFSTE"
    android:layout_width="220dp"
    android:layout_height="80dp"
    android:layout_alignLeft="@+id/bFBE"
    android:layout_below="@+id/bFBE"
    android:layout_marginTop="20dp"
    android:text="@string/fste" />

and this is my Faculty Activity which displays the buttons: I use Intent to view ListView

public class Faculty extends Activity{

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

    //on the XML,this is the "searchFSTEHandler" i want to use to show ListView
    public void searchFSTEHandler(View target){
        Intent courseList = new Intent(this, HttpActivity.class);
        startActivity(courseList);
    }
}

and below is the "HttpActivity" class is the class that displays my ListView. This class read a php file which gets data from a MySQL server and converts to JSON data then parses it into a array list.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;

public class HttpActivity extends ListActivity {

public String f1 = "FSTE";




@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.faculty_course);


    new getHttp().execute();

    getHttp test =new getHttp();


    String strJsonData = test.doInBackground(f1);

    // Convert String JSON data to Java class
    ArrayList<Courses> arrayCourse= test.parseJsonData(strJsonData);

    //Create an ArrayAdapter which shows the ArrayList data
    this.setListAdapter(new ArrayAdapter<Courses>(this,android.R.layout.simple_list_item_1,arrayCourse));



}




private class getHttp extends AsyncTask<String, Void, String> {

  public getHttp() { 











  }

  @Override
    protected String doInBackground(String... faculty) {



    InputStream is = null;
    try {
        URL url = new URL("http://10.0.2.2/sqlWebService.php?faculty=FSTE");
        URLConnection con = url.openConnection();
        con.setConnectTimeout(10000);
        con.setReadTimeout(10000);
        is = con.getInputStream();

        BufferedReader br = new BufferedReader(
                new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        String str;
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        return sb.toString();

    } catch (IOException e) {
        e.printStackTrace();
        return "";

    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }


}

//------------------------------------------------------  
  private ArrayList<Courses> parseJsonData(String strJson) {
        ArrayList<Courses> Course = new ArrayList<Courses>();

        try {
            // Generate JSONArray object by JSON String data
            JSONArray arr = new JSONArray(strJson);

            //from the JSONArray, get one element (row) of JSONData
            for (int i = 0; i < arr.length(); i++) {

                //Get JSON Object which is one element of the array
                JSONObject ob = arr.getJSONObject(i);

                Courses exam = new Courses();
                //get the value by key, and set to exam class
                exam.setCode(ob.optString("code"));

                //save exam class to exam array list
                Course.add(exam);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return Course;
    }





 }









 } 

The application crashes as soon as I click on the button and gives a error: "android.os.NetworkOnMainThreadException"

Help Please !

The problem that you are having is network operation like what you are trying to do cannot and should not be performed on the main UI thread. Doing so will lead to an ANR (Android Not Responding) , which is exactly the kind of error you are getting just now. What you want to do is move your code to a separate thread or to an AsyncTask that will perform this action in the background on a different thread using the doInBackground() method which does not have access to your views on the main UI thread. For example,

private class ExampleOperation extends AsyncTask<String, Void, String> {

    public ExampleOperation() { //ctor }

    @Override
    protected void onPreExecute() {
        //things that you want to initialize and maybe show dialog to user.
    }

    @Override
    protected String doInBackground(String... params) {
       //this is where you perform that network related operation.  
    }

    @Override
    protected void onPostExecute(String result) {
       //this is where get the results from the network related task.
    }

    @Override
    protected void onProgressUpdate(Void... values) {
       //you can update your progressbar if any; otherwise omit method.
    }

}

Then all you have to do is call the AsyncTask where ever you want to use it: new ExampleOperation().execute();

You can't make HTTP calls in the main thread, they take too long and would make the UI unresponsive. You need to do it in an AsyncTask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM