【问题标题】:Android, random from external jsonAndroid,随机来自外部 json
【发布时间】:2016-08-29 18:08:06
【问题描述】:

我正在开发一个安卓应用程序。我希望应用程序从 json 中随机选择一个名称。 这是json:

{
"user": [
{
"id": "001",
"name": "Raj Amal",
"email": "raj.amalw@gmail.com"
},
{
"id": "002",
"name": "Raj",
"email": "amalw@gmail.com"
}
]
}

这是我的安卓代码:

public class MainActivity extends Activity {
	TextView uid;
	TextView name1;
	TextView email1;
	Button Btngetdata;
	
	//URL to get JSON Array
	private static String url = "http://weblink/json/index.php";
	
	//JSON Node Names 
	private static final String TAG_USER = "user";
	private static final String TAG_ID = "id";
	private static final String TAG_NAME = "name";
	private static final String TAG_EMAIL = "email";
	
	JSONArray user = null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      
        setContentView(R.layout.activity_main);
        Btngetdata = (Button)findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View view) {
		         new JSONParse().execute();

				
			}
		});
        
        
    }


    
    private class JSONParse extends AsyncTask<String, String, JSONObject> {
    	 private ProgressDialog pDialog;
    	@Override
        protected void onPreExecute() {
            super.onPreExecute();
             uid = (TextView)findViewById(R.id.uid);
			 name1 = (TextView)findViewById(R.id.name);
			 email1 = (TextView)findViewById(R.id.email);
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            
    	}
    	
    	@Override
        protected JSONObject doInBackground(String... args) {
    		JSONParser jParser = new JSONParser();

    		// Getting JSON from URL
    		JSONObject json = jParser.getJSONFromUrl(url);
    		return json;
    	}
    	 @Override
         protected void onPostExecute(JSONObject json) {
    		 pDialog.dismiss();
    		 try {
    				// Getting JSON Array
    				user = json.getJSONArray(TAG_USER);
    				JSONObject c = user.getJSONObject(0);
    				
    				// Storing  JSON item in a Variable
    				String id = c.getString(TAG_ID);
    				String name = c.getString(TAG_NAME);
    				String email = c.getString(TAG_EMAIL);
    				
    				
    				//Set JSON Data in TextView
    				uid.setText(id);
    				name1.setText(name);
    				email1.setText(email);

    			
    		} catch (JSONException e) {
    			e.printStackTrace();
    		}

    		 
    	 }
    }`

我希望当我按下按钮时会随机显示一个名称并循环播放。

请帮忙 谢谢你

【问题讨论】:

  • 创建名称列表并使用随机数从列表中选择名称
  • 感谢您的回答,这就是我正在尝试做的我需要选择一个随机 id 并显示具有相同 id 的名称。但我真的不知道怎么感谢你

标签: android json random


【解决方案1】:

通过这一行更改JSONObject c = user.getJSONObject(0); ->

JSONObject c = user.getJSONObject(new Random().nextInt(user.length()));

【讨论】:

    【解决方案2】:

    你需要从你的数组中生成随机数 首先尝试在临时 Arraylist 中添加项目。我只是添加您需要替换名称而不是字符的字符

    String json="{'abridged_cast':
    [{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},  
    {'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},  
    {'name':'JessicaLange','id':'162653068','characters':['Dwan']},
    {'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},
    {'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";
    
    JSONObject jsonResponse;
    try {
         temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast"); // add 
        //user here instead of abridged_cas
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters"); // replace 
            //name instead of characters
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    您可以使用 onclick 或任何您想要的方式随机获取名称。

    Random randomizer = new Random();
    String RandomName = temp.get(randomizer.nextInt(temp.size()));
    

    【讨论】:

      【解决方案3】:

      遍历 JSON 输入。您可以使用 java 函数 int random = Random.nextInt(n)。这将返回范围 [0, n-1] 中的随机 int。

      ArrayList<String> names = new ArrayList<>();
      JSONArray socialArray = response.getJSONArray(data);
            for (int i = 0; i < socialArray.length(); i++) {
                  JSONObject currentJSON = socialArray.getJSONObject(i);
                  names.add(currentJSON.getString("name");
            }
      final int random = Random.nextInt(names.size() + 1); 
      Toast.makeText(this, "Random Name: " + names.get(random), LENGTH.SHORT).show();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多