user3380879
user3380879

Reputation: 1

Android, random from external json

I am working on an android app. I want the app to select randomly a name from json. Here is the json :

{
"user": [
{
"id": "001",
"name": "Raj Amal",
"email": "[email protected]"
},
{
"id": "002",
"name": "Raj",
"email": "[email protected]"
}
]
}

And here is my android code :

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();
    		}

    		 
    	 }
    }`

I would that when I presse the button a random name shows and loops.

Please help Thank you

Upvotes: 0

Views: 1058

Answers (3)

suku
suku

Reputation: 10929

Loop through the JSON input. You can use java function int random = Random.nextInt(n). This returns a random int in range[0, n-1].

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();

Upvotes: 0

Zahidul Islam
Zahidul Islam

Reputation: 3190

Change JSONObject c = user.getJSONObject(0); by this line ->

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

Upvotes: 1

Nowshad
Nowshad

Reputation: 294

you need to generate Random number from your array first try this to add items in temp Arraylist. i am just only adding characters you need to replace name instead of characters

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();
}

here is you get names randomly using onclick or whatever you want.

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

Upvotes: 0

Related Questions