在我的项目中,我使用排球库来获取数据,并根据这些数据我将添加按钮,按钮显示正确,但问题是打开另一个活动不起作用:
RequestQueue requestQueue;
TextView txt;
final int MY_REQ_CODE = 12345;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
final GridLayout layout = (GridLayout) findViewById(R.id.layout);
requestQueue = Volley.newRequestQueue(this.getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "url", null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonanswer = response.getJSONObject("answer");
final String[] name=new String[9];
txt = (TextView) findViewById(R.id.name);
JSONArray result = jsonanswer.getJSONArray("result");
for (int i=0;i<jsonArrayresult.length();i++){
JSONObject objresp = result.getJSONObject(i);
String name= objresp.getString("name");
name[i] = name;
}
for (int i=0;i<titles.length;i++){
Button btn = new Button(getApplicationContext());
btn.setText(titles[i]);
layout.addView(btn);
btn.setOnClickListener(getProducts);
btn.setTag(titles[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
View.OnClickListener getProducts = new View.OnClickListener() {
@Override
public void onClick(View v) {
Object tag = v.getTag();
Intent intent = new Intent(getApplicationContext(), otherActivity.class);
intent.putExtra("name", tag.toString());
startActivity(intent);
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == MY_REQ_CODE) {
if (resultCode == RESULT_OK) {
//??
} else if (resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Result canceled", Toast.LENGTH_SHORT).show();
}
}
}
我的第二项活动是:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products_list);
setResult(RESULT_OK);
finish();
final Intent intent = getIntent();
final TextView txt = (TextView) findViewById(R.id.txt);
Bundle title = intent.getExtras();
if (title != null) {
str = title.getString("title");
}
txt.setText(str);
}
答案 0 :(得分:1)
在内部活动之间移动时,您应该使用startActivity(intent)方法而不是startActivityForResult。
变化:
startActivityForResult(intent, MY_REQ_CODE);
要:
startActivity(intent);
<强>更新强> 从我所看到的你还创建了一个名为btn的新按钮,但是你将听众分配给其他按钮。我不知道你在哪里创建 btncategorie 按钮,它应该是:
Button btn = new Button(getApplicationContext());
btn.setText(titles[i]);
btn.setOnClickListener(getProducts);
btn.setTag(titles[i]);
layout.addView(btn);