背景:我正在尝试开发我的第一个Android应用程序,这是一个学生讨论小组。我很擅长PHP和MySQL,但在android Java方面没有太多经验。
问题: 在SelectedQuestionActivity类中,如果我只是将URL指定为http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid=3,它就可以正常工作并获取相应的问题答案。 但是,如果我按照下面代码中显示的方式执行此操作,应用程序将崩溃。我不确定我错在哪里。
CODE: AllQuestionActivity.java
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.qid)).getText()
.toString();
//pid is the value of the selected question for example www.example.com/fetchans?qid=3 so here pid value is supposed to be 3.
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SelectedQuestionActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
startActivity(in);
}
});
现在在SelectedQuestionActivity.java中 代码:
public class SelectedQuestionActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
Intent intent = getIntent();
String qid = intent.getExtras().getString(TAG_PID);
// url to get all products list
private String url_all_products = "http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid="+qid;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "ques";
private static final String TAG_PID = "aid";
private static final String TAG_NAME = "aname";
private static final String TAG_INFO = "answer";
private static final String TAG_DATE = "date";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SelectedQuestionActivity.this);
pDialog.setMessage("Loading Answers. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Answers: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String info = c.getString(TAG_INFO);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_INFO, info);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
productsList.add(map);
}
}
else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SelectedQuestionActivity.this, productsList,
R.layout.list_selected_ques, new String[] { TAG_PID,
TAG_NAME, TAG_INFO, TAG_DATE },
new int[] { R.id.aid, R.id.aname, R.id.answer, R.id.date});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
JSONparser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
答案 0 :(得分:2)
目前你正在尝试在ListActivity的onCreate之外的getIntent,所以将它移到onCreate方法中:
Intent intent;
String qid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// get Intent here
intent = getIntent();
qid = intent.getExtras().getString(TAG_PID);
// your code here
并且也不需要使用runOnUiThread
方法从onPostExecute
更新UI,因为在Ui线程上调用onPostExecute方法我们可以访问其中的UI元素
修改: - 强>
您没有在doInBackground中向NameValuePair添加任何参数。在将它发送到makeHttpRequest之前添加quid为:
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
add quid param here
params.add(new BasicNameValuePair("qid",qid)); //<<<< add here
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(
url_all_products,
"GET",
params);
// your code here
答案 1 :(得分:0)
您正在将一个字符串从一个活动对象传递到另一个活动对象,而您没有编写代码以在正确位置的新活动上接收它。 要解决此问题,您应该在onCreate中添加一些代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
String url = getIntent().getStringExtra(TAG_PID);
if (url != null)
url_all_products = url;
答案 2 :(得分:0)
您需要在onCreate()
中获取您的意图值,如下所示:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.all_ans); Intent intent = getIntent(); String qid = intent.getExtras().getString(TAG_PID); }