2016-11-17 104 views
0

我從服務器JSON數據。我將它轉換爲一個字符串數組並將其傳遞給下一個活動。我想在recyclerview中顯示這個數組。但只要我點擊按鈕,應用程序停止。這是我的顯示類的代碼。如何在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; 
    } 
} 
+0

能否請您發表logcat的錯誤? –

+0

請貼上logcat。 –

+0

@choi看起來像getarray是null? – Raghavendra

回答

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); 
        } 
+0

但getarray是我通過意圖傳遞的字符串數組。爲什麼使用JSONObject? – choi

+0

爲什麼你的事情上面一行是行不通的 –

+0

我上面的代碼更改,並嘗試 –

0

入住郵差 extention您正在使用的網址,並檢查是否你得到它的反應是有效的,你會得到它。

相關問題