Exctracting more than one field at time from a JSon file - java

I was developing a simple application that exctracts some fields of a JSon that tells me in real time what weather is in that exact moment, and I have exctracted only one filed, and I was asking myself: Is it possible to extract more than on field at time?
Here is the the link from where i parse the Json:
https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139
And here's my code:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
ArrayMap<Integer, String> arrayMap = new ArrayMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139");
}
});
}
public class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
try {
JSONObject Object = new JSONObject(result);
JSONArray arr = new JSONArray(Object.getString("weather"));
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
//txtJson.append("main: " + jsonPart.getString("main") + '\n');
arrayMap.put(i, jsonPart.getString("main"));
txtJson.append("main: " + arrayMap.get(i) + '\n');
}
} catch (JSONException e) {
e.printStackTrace();
//txtJson.setText(result);
}
//txtJson.setText(result);
}
}
}

If I understand correctly you want to extract other object alongwith main from the array weather
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F50n.png?1499366021876"
}
If that is the requirement then you can use the same process like you have done just change the name of the object.
arrayMap.put(i, jsonPart.getString("description"));
or
you can use gson and convert the object in pojo class in one go. Then use the object of the pojo and access the data.
Hope it helps.

Related

I got error Android JSON parsing Retrieve from URL

I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)
Error shows this line textView.setText(jsonObject.getString("distance"));
My Code
HttpResponse httpResponse;
Button button;
TextView textView;
static JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
new GetDataFromServerIntoTextView(MainActivity.this).execute();
}
});
}
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
String HttpURL = "https://api.myjson.com/bins/1cuzhn";
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textView.setText(jsonObject.getString("distance"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}
I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.
Add below dependencies
// OKHTTP
implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
and
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String>
{
public Context context;
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String strUrl = "https://api.myjson.com/bins/1cuzhn";
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, "Exception while downloading url " + e.toString());
} finally {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
try {
if (data != null) {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here is your all data of distance and time
Log.e(TAG, "distance " + jsonObject.get("distance"));
Log.e(TAG, "time " + jsonObject.get("time"));
}
} else {
Log.e(TAG, "onPostExecute: null json object");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are using POST request where as your api is expecting GET request
Here is more details about GET and POST
HttpPost httpPost = new HttpPost(HttpURL);
replace this with following
HttpGet request = new HttpGet(HttpURL);
To avoid crash replace your code with
textView.setText(jsonObject.getString("distance"));
this
textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));

Is it possible that the array map is too little for contain about 2000 items?

In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.

Making Attendance App in Android

I have to make attendance app for college.The app will take data from colleges website and display it on app according to user login and password.
When we login into college's website we have to put id and password, same thing I want on my app so that user can see it on an app itself.
I have searched httpurlconnection, httpget, httppost, jsoup.
Up till now, I have understood that I have to make httprequest for loading the college's attendance site and then httppost to post username and password and after that jsoup to grab the data from HTML page.
But I have seen tutorials only to request JSON pages, but how to request for HTML pages?and post login to it?
Here is what I tried and collected data from JSON
private TextView textresponse1;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Get= (Button) findViewById(R.id.httprequest);
textresponse1= (TextView)findViewById(R.id.textresponse);
progressDialog=new ProgressDialog(this);
Get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
progressDialog.setMessage("Collecting Data");
progressDialog.show();
}
public class JSONTask extends AsyncTask<String,String,String >{
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
String line="";
StringBuffer buffer=new StringBuffer();
while ((line = reader.readLine())!=null) {
buffer.append(line);
}
String finaljosn=buffer.toString();
StringBuffer add =new StringBuffer();
JSONObject parentobject=new JSONObject(finaljosn);
JSONArray parentarray=parentobject.getJSONArray("movies");
for(int i=0;i<parentarray.length();i++) {
JSONObject moviename = parentarray.getJSONObject(i);
String finalmovie = moviename.getString("movie");
int finalyear = moviename.getInt("year");
add.append(finalmovie +"- "+finalyear + "\n");
}
return add.toString();
// return finalmovie +" -Rushabh- " +finalyear;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection!=null) {
connection.disconnect();
}
try {
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
textresponse1.setText(result);
}
}
String mLoadURL="http://www.google.com";
public class LoadHtml extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(mLoadURL);
StringBuilder stringBuilder = new StringBuilder();
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!s.trim().isEmpty()) {
//load html to webview
}
}
}
Call Above AsyncTask using:
LoadHtml loadHtml= new LoadHtml();
load.execute();

Android - put data into array in asynctask

I got a question that I don't know how to solve.
I am trying to achieve putting the 'question' and 'answer' into the 2D Array, but it cannot put the data into the 2D array in the asyncTask.
I am expecting I can put the 'question' and 'answer' that get in JSON Object into the 2D array. And then use the array in OnCreate method.
public class MainActivity extends Activity {
String[][] array = new String[10][4];
private TextView tvData;
int qnum = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
String quest;
String ans;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new JSONTask().execute("http://itdmoodle.hung0530.com/ptms/questions_ws.php");
Button btnNext = (Button) findViewById(R.id.btnNext);
tvData = (TextView) findViewById(R.id.textView);
for(int i=0;i<10;i++){
int z = i+1;
array[i][0] = String.valueOf(z);
}
quest = array[0][1];
ans = array[0][2];
tvData.setText(quest);
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
public class JSONTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream stream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String Json = buffer.toString();
JSONObject jsonObject = new JSONObject(Json);
JSONArray jsonArray = jsonObject.getJSONArray("Questions");
StringBuffer bufferQues = new StringBuffer();
StringBuffer bufferAns = new StringBuffer();
for(int i=0;i<jsonArray.length();i++) {
JSONObject otherJson = jsonArray.getJSONObject(i);
String question = otherJson.getString("question");
String answer = otherJson.getString("answer");
bufferQues.append(question);
bufferAns.append(answer);
array[i][1] = bufferQues.toString();
array[i][2] = bufferAns.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(conn != null){
conn.disconnect();
}
try{
if(reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
}
Asynctask executes asynchronously. It allows you to perform long running operations on a background thread(doInBackground is run on a seperate thread than main thread) and use the results to perform operations on main thread(onPostExecute runs on main thread).
What you want is to perform the operation on your 2D array in onPostExecute and not in onCreate.

Widget is not updating after JSON parse

I have the following code:
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Toast.makeText(context, "onReceiver()", Toast.LENGTH_LONG).show();
}
new GetJSON().execute(null, null, null);
}
public class GetJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) { //Running in background
try {
httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/hadith.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("TEST", e.toString());
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return null;
}
#Override
protected void onPreExecute() { //Activity is on progress
}
#Override
protected void onPostExecute(Void v) {
try {
jsonArray = new JSONArray(result);
date = new String[jsonArray.length()];
quote = new String[jsonArray.length()];
by = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject) jsonArray.get(i);
date[i] = jsonObj.getString("Date");
quote[i] = jsonObj.getString("Quote");
by[i] = jsonObj.getString("By");
} // End the for loop
views.setTextViewText(R.id.tvToday, date[0]);
views.setTextViewText(R.id.tvParkStatus, quote[0]);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
I am looking to update the widget with the information received from the JSON file. I see the widget but no information is being displayed.
My JSON looks like:
[
{
"Date" : "11182013",
"Quote" : "Today Is Monday",
"By" : "SiKni8"
},
{
"Date" : "11192013",
"Quote" : "Today Is Tuesday",
"By" : "SiKni8"
}
]
Change your AsynkTast to:
public class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected Void doInBackground(Void... params) { //Running in background
// ...
// do all your stuff as it is and change return to this :
return result;
}
#Override
protected void onPostExecute(String result) {
// left other of your code as it is.
}
}
And change execution to new GetJSON().execute();

Categories

Resources