retrofit2从mysql获取数据并在listview上显示

时间:2017-02-09 14:41:21

标签: android mysql listview retrofit2

我正在尝试使用服务器端的Retrofit2和PHP从MySQL获取数据。在textview上显示没有问题,然后我试图在listview上展示,但我总是得到并且错误。有人可以帮我解决吗?你能解释一下如何使用listviewArrayAdapter吗?

MainActivity

public class MainActivity extends AppCompatActivity {

    EditText editName, editAddress;
    //TextView textDetails;
    Button btnGetData, btnInsertData;
    private ProgressDialog pDialog;
    String[] details = {"asd"};
    ListView list;
    ArrayAdapter<String> add;
    //ArrayAdapter add = new ArrayAdapter<String> (this,R.layout.datalist,details);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //textDetails = (TextView)findViewById(R.id.textView);
        editName = (EditText)findViewById(R.id.editName);
        editAddress = (EditText)findViewById(R.id.editAdress);
        btnGetData = (Button)findViewById(R.id.btnGetData);
        btnInsertData = (Button)findViewById(R.id.btnInsert);
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please wait.....");
        pDialog.setCancelable(false);

        getPeopleDetails();
        add = new ArrayAdapter<String> (this,R.layout.datalist,details);
        //textDetails.setText(details);
        list = (ListView)findViewById(R.id.list);
        list.setAdapter(add);

        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPeopleDetails();

            }
        });
        btnInsertData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setStudentDetails();
            }
        });
    }

    private void getPeopleDetails(){
        showpDialog();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.0.101/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        APIService service = retrofit.create(APIService.class);

        Call<List<Student>> call = service.getPeopleDetails();

        call.enqueue(new Callback<List<Student>>() {
            @Override
            public void onResponse(Call<List<Student>> call, Response<List<Student>> response) {
                List<Student> students = response.body();

                for (int i = 0 ; i < students.size(); i++){
                    String name = students.get(i).getName();
                    String address = students.get(i).getAddress();
                    details[i]="nama  : "+name;
                }
                //hidepDialog();
                //ArrayAdapter add = new ArrayAdapter<String> (this,R.layout.datalist,details);
                list.setAdapter(add);

                hidepDialog();
                //return;
                //Toast.makeText(MainActivity.this,details,Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<List<Student>> call, Throwable t) {
                hidepDialog();
                Toast.makeText(MainActivity.this,"ora metu opo2",Toast.LENGTH_LONG).show();
            }
        });
    }

    private void setStudentDetails(){
        showpDialog();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.0.101")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        APIService service = retrofit.create(APIService.class);
        Student student = new Student();
        student.setName(editName.getText().toString());
        student.setAddress(editAddress.getText().toString());
        Call<Student> call = service.insertStudentInfo(student.getName(),student.getAddress(),"081805854466" );
        call.enqueue(new Callback<Student>() {
            @Override
            public void onResponse(Call<Student> call, Response<Student> response) {
                hidepDialog();
                Toast.makeText(MainActivity.this,"insert data ok",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<Student> call, Throwable t) {
                hidepDialog();
                Toast.makeText(MainActivity.this,t.toString(),Toast.LENGTH_LONG).show();
            }
        });
    }
    private void showpDialog(){
        if(!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog(){
        if (pDialog.isShowing())
            pDialog.hide();
    }
}

APIService

public interface APIService {
    @GET("student/list.php")
    Call<List<Student>> getPeopleDetails();

    @FormUrlEncoded
    @POST("student/insertst.php")
    Call<Student> insertStudentInfo(@Field("name") String name, @Field("address") String address, @Field("mobile") String mobile);
}

public class Student {
    private String name, address;
    private String mobile;

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.idabdull.retrofit_try.MainActivity"
    android:orientation="vertical">

    <Button
        android:text="Get Data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnGetData" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="275dp"
        android:id="@+id/list" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="Name"
        android:ems="10"
        android:id="@+id/editName" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="Address"
        android:ems="10"
        android:id="@+id/editAdress" />

    <Button
        android:text="Insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnInsert" />
</LinearLayout>

detailist.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:id="@+id/label"
    android:padding="10dip"
    android:textSize="16dip"
    android:textStyle="bold">
</TextView>

和错误

java.lang.ArrayIndexOutOfBoundsException: length=1; index=-1
                      at com.example.idabdull.retrofit_try.MainActivity$3.onResponse(MainActivity.java:94)
                      at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5264)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
I/Process: Sending signal. PID: 23765 SIG: 9

1 个答案:

答案 0 :(得分:0)

String数组中的问题。在java中,n数组是一个容器对象,它包含单个类型的固定数量值。这意味着在您尝试在方法中进行初始化后,无法更改其长度。 在你的例子中

String[] details = {"asd"}; // details.length is 1

您必须使用onResponse方法初始化数组,如下所示

  @Override
        public void onResponse(Call<List<Student>> call, Response<List<Student>> response) {
            List<Student> students = response.body();
            details = new String[students.size()]; // here you know lenght of needed array

            for (int i = 0 ; i < students.size(); i++){
                String name = students.get(i).getName();
                String address = students.get(i).getAddress();
                details[i]="nama  : "+name;
            }
            // your code 
        }