Android JSON only OBJECT Fetching with Iteration - java

I have a json file which contains only objects now i cant able to fetch all the object with iteration as here is no array.
Here is the code : That i have tried in my android studio & JSon Data Screenshot
#Override
protected String doInBackground(String... strings) {
try {
url = new URL("https://api.myjson.com/bins/r7dj6");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line =" ";
while ((line = bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
String fullfile = stringBuffer.toString();
JSONObject jsonObject = new JSONObject(fullfile);
JSONObject jsonObjectchild = jsonObject.getJSONObject("Apartment");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

Here is a complete example. Works for me.
HttpURLConnection connection = null;
try {
URL url = new URL("https://api.myjson.com/bins/r7dj6");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder stringBuffer = new StringBuilder();
while ((line = reader.readLine()) != null){
stringBuffer.append(line);
}
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
JSONObject apartmentObject = jsonObject.getJSONObject("Apartment");
Iterator<String> keys = apartmentObject.keys();
while (keys.hasNext()) {
String flatName = keys.next();
JSONObject flat = apartmentObject.getJSONObject(flatName);
String age = flat.getString("age");
String color = flat.getString("color");
String name = flat.getString("name");
String owner = flat.getString("owner");
String partner = flat.getString("partner");
Log.d("Flat", flatName + ": " + age + ", " + color + ", " + name + ", " + owner + ", " + partner);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}

You can still iterate:
for (Iterator key=jsonObjectchild.keys();key.hasNext();) {
JSONObject flatName = json.get(key.next());
...
}

Related

I am getting mismatch in json data after parsing it from API

I am trying to parse a json api for Covid19. The link is available in the code . The data I am getting does not match with the original JSON file.(for eg: there is a mismatch in the stats for the district "Rohtas" and many more)
public static void getAllDistrictsInfo()
{
ArrayList<StateDetails> states = new ArrayList<StateDetails>();
try{
URL url = new URL("https://api.covid19india.org/state_district_wise.json");//your url i.e fetch data from .
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
Scanner sc = new Scanner(url.openStream());
String inline = "";
while(sc.hasNext())
{
inline+=sc.nextLine();
}
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject)parse.parse(inline);
ArrayList<String> set = new ArrayList<String>(jobj.keySet());
for(Iterator iterator = set.iterator(); iterator.hasNext();)
{
String key = (String) iterator.next();
JSONObject distdata = (JSONObject) jobj.get(key);
JSONObject dists = (JSONObject) distdata.get("districtData");
System.out.println(key);
ArrayList<String> set2 = new ArrayList<String>(dists.keySet());
for(Iterator itr = set2.iterator();itr.hasNext();)
{
String key2 = (String) itr.next();
JSONObject district = (JSONObject) dists.get(key2);
System.out.println(key2);
System.out.println(district);
}
System.out.println("************");
}
conn.disconnect();
}
catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
}

http post request return 401 when the auth credential are correct -

I'm having this issue for posting data only, I got 401 (non-authorized) while my credential are correct! how to fix this?
ttpURLConnection urlConnection;
IgnoreSSL();
String url = null;
url = "http://" + nmap_node.getHost() + ":"+nmap_node.getPort() + "/post";
String result = null;
try {
String userpass = user_name + ":" + password; //stored in the class
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//Connect
urlConnection = (HttpURLConnection) ((new URL(url).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+basicAuth);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
//data
String data = datajson.toString(); //method return json to use
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I tried in Linux with curl command It works perfectly - I got respond 200 and printed results in the screen.

File reading from controller

I have 2 almost identical methods. But 1 can see my file , another not.It skips the method body with line = null. Dont understand why.
This doesnt work
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("file") MultipartFile file, Model model) {
if (!file.isEmpty()) {
try {
String path = "d:/" + file.getOriginalFilename();
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(path)));
stream.write(bytes);
model.addAttribute("list", addRecordsToBD(path));
stream.close();
} catch (Exception e) {
log.error("Upload failed", e);
}
}
return "show";
}
private List addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
repository.saveAndFlush(new User(users[0], users[1], users[2],
users[3], users[4]));
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
return repository.findAll();
}
But this work great
public void addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
System.out.println("User [Name = " + users[0] +
", surname = " + users[1] +
" login = " + users[2] +
" mail = " + users[3] +
" phone = " + users[4] +
"]");
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
}
}
Can some one explain me, what's the problem and why this happened ?

Mysql insert statement and passing parameters to PHP

I am trying to execute various statements/queries in my PHP file, depending on what variables are received (moreover, is there a way to send variables and choose what kind of query I want to do, as opposed to making one query for each set of variables received? This is my first time writing in PHP so please forgive the possible stupid question).
In this case its a Username, Password, and UserID. I'd like an insert to occur when these 3 variables are received. However, I keep on receiving an error: java.net.ProtocolException: method does not support a request body: GET (this is when conn.setDoOutput isset to true). If I have it set to false, I get a IO URL error which states my URL cannot be found. What am I doing wrong? Below are both my php script and the java code used for GET requests.
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['Username']) && isset($_Get['Password']) && isset($_GET['UserID'])){
$uname = mysql_real_escape_string($_GET['Username']);
$pass = mysql_real_escape_string($_GET['Password']);
$uid = intval($_GET['UserID']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
Since this PHP script does an INSERT statement, it's strongly recommended that you use POST parameters.
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = "&" + URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP script:
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['un']) && isset($_POST['pw']) && isset($_POST['uid'])){
$uname = mysql_real_escape_string($_POST['un']);
$pass = mysql_real_escape_string($_POST['pw']);
$uid = intval($_POST['uid']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
As an aside, for a GET request, you just append the parameters to the end of the url when you create the URL object.
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
String urlString = "phpfilelocation.php" + "?" + data;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.connect();
//remove:
//OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//wr.write(data);
//wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP :
mysql_query("INSERT INTO Users(id, UserName, Password)
VALUES ('$uid', '$uname', '$pass')");
JAVA :
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String unameDB="username";
String passDB="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,unameDB,passDB);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `Users`(ID,UserName,Password) VALUE ('"+uid+"','"+uname+"','"+pass+"')");

Creating JSONObject from text file

I am attempting to read a text file and create a JSONObject in an Android application, but after reading the text file into a string, I get a JSONException thrown when I try to construct a JSONObject using the string.
Here is the code I am using:
InputStream is = this.getResources().openRawResource(R.raw.quiz);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String jsString = "";
String line = null;
while((line = reader.readLine()) != null){
jsString += line;
}
is.close();
reader.close();
try {
return new JSONObject(jsString);
} catch (JSONException e) {
}
return null;
Here is the text file I am reading from, quiz.txt:
{"length":3,"questions":[{"questionText":"Is mayonaise an instrument?","answers":["Yes","no","no","no","no"],"correctAnswer":0},{"questionText":"10^2","answers":["1","10","100","1000","over 9000"],"correctAnswer":1},{"questionText":"Dogs Name?","answers":["Barky","Steve","Rex","Daisy","Wormy"],"correctAnswer":3}]}
Try using this method to read the file contents into a string.
public static String getJsonFromResource( int resource, Context context ) {
InputStream inputStream = context.getResources().openRawResource( resource );
BufferedReader r = new BufferedReader( new InputStreamReader( inputStream ) );
StringBuilder stringBuilder = new StringBuilder();
String line;
String jsonString = null;
try {
while (( line = r.readLine() ) != null) {
stringBuilder.append( line );
}
jsonString = stringBuilder.toString();
}
catch (Exception e) {
Log.e( "GetJsonFromResource", Log.getStackTraceString( e ) );
}
return jsonString;
}

Categories