如何在recyclerview中显示字符串数组?

时间:2016-11-17 06:12:25

标签: android android-recyclerview

我有来自服务器的json数据。我将它转换为字符串数组并将其传递给下一个活动。我想在recyclerview中显示这个数组。但是一旦我点击按钮,应用就会停止。这是我的显示类代码。

public class Display extends AppCompatActivity {

TextView displaytext;
String getarray[];
ArrayList<String> mylist;

private RecyclerView rview;
private RecyclerView.LayoutManager layoutManager;
private Adapter madapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);


    //displaytext = (TextView) findViewById(R.id.textView);

    rview = (RecyclerView) findViewById(R.id.recyclerview1);
    layoutManager = new LinearLayoutManager(this);
    rview.setLayoutManager(layoutManager);




    Bundle extras = this.getIntent().getExtras();
    if (extras != null) {
        getarray = extras.getStringArray("array");
        //The key argument here must match that used in the other activity


       mylist  = new ArrayList<String>(Arrays.asList(getarray));


    }

    madapter = new Adapter(mylist, getApplicationContext());
    rview.setAdapter(madapter);






}
}

适配器的代码。

public class Adapter extends RecyclerView.Adapter<Adapter.MyHolder> {



ArrayList<String> mylist;

private Context context;
private LayoutInflater inflater;
//List<Data> datas = Collections.emptyList();
Data current;
int currentpos = 0;

//create constructor to initializ context and data sent from main activity.
public Adapter(ArrayList<String> mylist, Context context){

    this.mylist = mylist;

}




@Override
public Adapter.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {


    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.container_data, parent, false);
    MyHolder holder = new MyHolder(view);
    return holder;


}

@Override
public void onBindViewHolder(MyHolder holder, int position) {

    holder.textData.setText(mylist.get(position).toString());

}

 @Override
public int getItemCount() {
    return mylist.size();
}

class MyHolder extends RecyclerView.ViewHolder{

    TextView textData;

    //contructor for getting reference to the widget
    public MyHolder(View itemView){
        super(itemView);

        textData =(TextView) itemView.findViewById(R.id.textdata);




    }


}

这些是我在调试时发现的错误。

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.aadesh.jesus, PID: 30964
              java.lang.NullPointerException
                  at com.example.aadesh.jesus.MainActivity$2.onResponse(MainActivity.java:190)
                  at com.example.aadesh.jesus.MainActivity$2.onResponse(MainActivity.java:162)
                  at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                  at android.os.Handler.handleCallback(Handler.java:733)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:146)
                  at android.app.ActivityThread.main(ActivityThread.java:5511)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                  at dalvik.system.NativeStart.main(Native Method)

这是主要活动的代码。

public class MainActivity extends AppCompatActivity {



    //private String urlJsonObj = "http://walletuncle.com/myservice.asmx/UserLogin";

    // json array response url
   // private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";

    private static String TAG = MainActivity.class.getSimpleName();
    private Button btnMakeObjectRequest, btnMakeArrayRequest;

    // Progress dialog
    private ProgressDialog pDialog;

    private TextView txtResponse;

    private EditText editusername;
    private EditText editpassword;

    String username;
    String password;


    public static final String KEY_USERNAME = "UserId";
    public static final String KEY_PASSWORD = "Password";


    int i=0;



    // temporary string to show the parsed response
    private String jsonResponse;

    private String DataArray[];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnMakeObjectRequest = (Button) findViewById(R.id.btnObjRequest);
       // btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
       // txtResponse = (TextView) findViewById(R.id.txtResponse);

        editusername = (EditText) findViewById(R.id.editusername);
        editpassword = (EditText) findViewById(R.id.editpassword);

        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);



        btnMakeObjectRequest.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // making json object request
                makeJsonObjectRequest();
            }
        });


    }

    private void makeJsonObjectRequest() {

     username = editusername.getText().toString().trim();
     password = editpassword.getText().toString().trim();



        String uri = String.format("http://walletuncle.com/myservice.asmx/UserLogin?UserId=%1$s&password=%2$s",
                username,
                password);





      /*  StringRequest stringRequest = new StringRequest(Request.Method.POST, urlJsonObj,
                new Response.Listener<String>() {



                    @Override
                    public void onResponse(String response) {

                    Log.d("Data added", "Data done");

                    }

                },


                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_USERNAME, username);
                params.put(KEY_PASSWORD, password);



                return params;
            }
        };

        AppController.getInstance().addToRequestQueue(stringRequest);*/




                showpDialog();

    final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            uri, null, new Response.Listener<JSONObject>() {

        public void onResponse(JSONObject response) {
            Log.d(TAG, response.toString());

            try {
                // Parsing json object response
                // response will be a json object // Parsing json object response
                // response will be a json object
              /*  String name = response.getString("Name");
                String phoneno = response.getString("phoneno");
                String comission = response.getString("comission");
                String Status = response.getString("Status");
                String memberid = response.getString("memberid");
                String mid = response.getString("mid");
                String card = response.getString("CARD");
                String msgcount = response.getString("msgcount");
                String walletAmount = response.getString("WalletAmount");
                String mtype = response.getString("mtype");
                String rewardPoints = response.getString("RewardPoints");
                String totalcusto = response.getString("totalcusto");
                String monthcusto = response.getString("monthcusto");
                String notify = response.getString("notify");
                String notification = response.getString("notification");*/




                DataArray[i]  = "Name" + ":" + response.getString("Name");
                DataArray [i+1] = "Phone no "+ ":"+response.getString("phoneno");
                DataArray [i+2] = "comission"+":"+ response.getString("comission");
                DataArray [i+3] = "Status" + ":" + response.getString("Status");
                DataArray [i+4] = "Member id"+":"+response.getString("memberid");
                DataArray [i+5] = "mid"+":"+response.getString("mid");
                DataArray [i+6] = "card"+":"+response.getString("CARD");
                DataArray [i+7] = "msg count"+":"+response.getString("msgcount");
                DataArray [i+8] = "wallet amount"+":"+response.getString("WalletAmount");
                DataArray [i+9] = "mtype"+":"+response.getString("mtype");
                DataArray [i+10] = "reward points"+":"+response.getString("RewardPoints");
                DataArray [i+11] = "total cust"+":"+response.getString("totalcusto");
                DataArray [i+12] = "month custo"+":"+response.getString("monthcusto");
                DataArray [i+13] = "notify"+":"+response.getString("notify");
                DataArray [i+14] = "notification"+":"+response.getString("notification");




                /*jsonResponse = "";
                jsonResponse += "Name: " + name + "\n\n";
                jsonResponse += "phone no: " + phoneno + "\n\n";
                jsonResponse += "Commission: " + comission + "\n\n";
                jsonResponse += "Status: " + Status + "\n\n";
                jsonResponse += "Member id: " + memberid + "\n\n";
                jsonResponse += "mid: " + mid + "\n\n";
                jsonResponse += "card: " + card + "\n\n";
                jsonResponse += "Message count: " + msgcount + "\n\n";
                jsonResponse += "Wallet Amount: " + walletAmount + "\n\n";
                jsonResponse += "mtype: " + mtype + "\n\n";
                jsonResponse += "Reward points: " + rewardPoints + "\n\n";
                jsonResponse += "Total customer: " + totalcusto + "\n\n";
                jsonResponse += "Month Customer: " + monthcusto + "\n\n";
                jsonResponse += "notify: " + notify + "\n\n";
                jsonResponse += "Notification: " + notification + "\n\n";*/


                Bundle b = new Bundle();
                b.putStringArray("array", DataArray);

                Intent intent = new Intent(getBaseContext(), Display.class);
                intent.putExtras(b);
                startActivity(intent);


                //txtResponse.setText(jsonResponse);

            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
            }
            hidepDialog();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_SHORT).show();
            // hide the progress dialog
            hidepDialog();
        }
    });

        //Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjReq);


    }


    /*protected String addparams(String urlJsonObj){

        if(!urlJsonObj.endsWith("?"))
          urlJsonObj += "?";

        List<Pair<String, String>> params = new ArrayList<>();
        params.add(new Pair<>("UserId", username));
        params.add(new Pair<>("Password", password));



        String paramString = URLEncodedUtils.format(params, "utf-8");

    }*/



    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

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


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.
                INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        return true;
    }
}

2 个答案:

答案 0 :(得分:0)

您从代码中替换此行

     mylist  = new ArrayList<String>(Arrays.asList(getarray));

以下代码

List<String> mylist= new ArrayList<String>();
   for (int i = 0; i < getarray.length(); i++) {
                        String data = getarray[i];
                        mylist.add(data );
                    }

答案 1 :(得分:0)

检查您正在使用的网址中的 POSTMAN 扩展名,并检查您获得的回复是否有效并获得该回复。