1

I'm trying to get data from MySQL using Retrofit2 and PHP on server side. Showing on textview is no issue and then I'm trying to show on listview but I always get and error. Could someone can help me fix it? Could you explain me how to use listview and ArrayAdapter?

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>

and error

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
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
abdullah
  • 33
  • 4

1 Answers1

0

The problem in your String array. In java n array is a container object that holds a fixed number of values of a single type. This means that you cannot change its length after initialization as you trying to do in your method. In you example

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

You have to init your array in the onResponse method like shown below

  @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 
        }
Volodymyr
  • 6,393
  • 4
  • 53
  • 84
  • if i delete this String[] details = {"asd"} i get error 'code'java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.idabdull.retrofit_try/com.example.idabdull.retrofit_try.MainActivity}: java.lang.NullPointerException: storage == null'code' – abdullah Feb 10 '17 at 16:04
  • You have to init your `details` array first by doing like this `String[] details = new String[0];` Or move your adapter initialization into `onResponse` method and set adapter there – Volodymyr Feb 10 '17 at 16:09
  • but i have new problem, after scroll listview then forceclose again and give error java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference – abdullah Feb 10 '17 at 16:28