android - 将字符串从一个 Activity 传递到另一个 Activity 时出现问题

标签 android android-intent

背景:我正在尝试开发我的第一个 Android 应用程序,它是一个学生讨论小组。我擅长 PHP 和 MySQL,但在 android Java 方面没有太多经验。

问题: 在 SelectedQuestionActivity 类中,如果我简单地将 URL 指定为 http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid=3 ,它工作得很好,它会获取问题的相应答案。 但是,如果我按照下面代码中所示的方式进行操作,应用程序就会崩溃。我不确定我哪里错了。

代码: 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);
            }
        });

    }

   }
  }

JSON解析器.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;

}
}

最佳答案

目前您正在尝试在 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

关于android - 将字符串从一个 Activity 传递到另一个 Activity 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14545971/

相关文章:

android - 带有 TextEdit header 的 ListView 搞砸了

android - 如何检查 Environment.DIRECTORY_DOCUMENTS 在 android 中为空

android - 通过 Android 中的深层链接将额外值传递给 Intent

android - 在 Android 中通过电子邮件发送图像的可能方式有哪些?

android - 如何从表面 View 内部完成 Activity?

java - setRequestedOrientation 在 react native 中找不到符号

android - 当应用程序处于后台时,我的 mvvm、livedata 应用程序是否应该取消网络请求?

android - 对相同 Activity 的警报

android - Android 中的 ACTION_SEND 和 Google+ 应用

android - 调整 EditText 大小以适合文本大小