Как отобразить массив строк в recyclerview?Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Как отобразить массив строк в recyclerview?

Сообщение Anonymous »

У меня есть данные в формате JSON с сервера. Я преобразовал его в массив строк и передал следующему действию. Там я хотел отобразить этот массив в recyclerview. Но как только я нажимаю кнопку, приложение останавливается. Вот мой код для класса отображения.

public class Display extends AppCompatActivity {

TextView displaytext;
String getarray[];
ArrayList 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(Arrays.asList(getarray));

}

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

}
}


Код адаптера.

public class Adapter extends RecyclerView.Adapter {

ArrayList mylist;

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

//create constructor to initializ context and data sent from main activity.
public Adapter(ArrayList 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/U ... sword=%2$s",
username,
password);

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

@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 getParams() throws AuthFailureError {
Map params = new HashMap();
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() {

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 = "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 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;
}
}


Подробнее здесь: https://stackoverflow.com/questions/406 ... cyclerview
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»