Simple weather app didn't work? - java

I am trying to display main and description from json data i take from opneweathermap. And nothing happen, but I don't have errors.
I will not include the link.
Here is my MainActivity class
public class MainActivity extends AppCompatActivity {
private Button mButton;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mTextView = (TextView) findViewById(R.id.textView2);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask task = new DownloadTask();
task.execute("Link");
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while(data != -1){
char current = (char) data;
result+=current;
data = inputStreamReader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Toast.makeText(getApplicationContext(), "Soem"+message,Toast.LENGTH_LONG).show();
Log.i("Weather content", weatherInfo);
JSONArray array = new JSONArray(weatherInfo);
for(int i=0;i<array.length();i++){
JSONObject jsonPart = array.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != ""){
message += main + ": " + description + "\r\n";
}
}
if(message != ""){
mTextView.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I have included uses-permissions and i have TextView and Button that will display the data from json in my layout file.

Related

Exctracting more than one field at time from a JSon file

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.

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.

Refresh json url when button pressed

I found out how i did what i asked in an earlyer question but i am wondering how i can reload URL url = new URL("https://www.lurkinator.net/api/data?username="+typedText+""); After the user presses a button? I have a button called "button" i want it to refresh the url since i have the typedText at the end and when user edits the edittext i want data to refresh from the api
Here is my code. And here is a screenshot of how the app looks so you have an idea.
Photo
public class MainActivity extends AppCompatActivity {
TextView points, username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
points = (TextView) findViewById(R.id.textView8);
username = (TextView) findViewById(R.id.textView9);
new getData().execute();
}
class getData extends AsyncTask<String, String, String> {
// get EditText by id and store it into "inputTxt"
EditText USERNAME = (EditText) findViewById(R.id.UserSet);
// Store EditText - Input in variable
String typedText = USERNAME.getText().toString();
HttpURLConnection urlConnection = null;
#Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://www.lurkinator.net/api/data?username="+typedText+"");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String line;
while ((line = br.readLine()) != null) {
result.append(line+"\n");
}
br.close();
String jsonString = result.toString();
System.out.println("JSON: " + jsonString);
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String t = jsonObject.getString("points");
String u = jsonObject.getString("username");
points.setText(t);
username.setText(u);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Thanks!
Add ok button click listener
Button clickButton = (Button) findViewById(R.id.clickButton);
clickButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
new getData().execute();
}
});

Global Variable returning to 0.0 after completion of an AsyncTask

The main part of this question is, when I run this code, the TextViews latitudeTextView and longitudeTextView get updated correctly, therefore the global variable are being change to the correct values. But when i try to access them again after going an asynctask, they are set to 0.0, 0.0? Shouldn't they stay as the same values after onPostExecute ends?
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Weather>{
private static final String GOOGLE_CONVERTER = "https://maps.googleapis.com/maps/api/geocode/json";
private static final String GOOGLE_KEY = "AIzaSyBtt8yaXoRvLTkJHUXrhl5pQaLxomReHIA";
public static final int LOADER_ID = 0;
String jsonResponse = "";
private String address;
private TextView latitudeTextView;
private TextView longitudeTextView;
private TextView summaryTextView;
private TextView tempuratureTextView;
private TextView timezoneTextView;
private TextView textTextView;
private double latitude = 0.0;
private double longitude = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTextView = (TextView) findViewById(R.id.latitude);
longitudeTextView = (TextView) findViewById(R.id.longitude);
summaryTextView = (TextView) findViewById(R.id.summaryTextView);
tempuratureTextView = (TextView) findViewById(R.id.temperatureTextView);
timezoneTextView = (TextView) findViewById(R.id.timezoneTextView);
textTextView = (TextView) findViewById(R.id.test);
final EditText addressEditText = (EditText) findViewById(R.id.edittext_address);
Button submitButton = (Button) findViewById(R.id.submit_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
address = addressEditText.getText().toString().trim();
address = "5121+Paddock+Court+Antioch+Ca+94531";
String fullUrl = GOOGLE_CONVERTER + "?address=" + address + "&key=" + GOOGLE_KEY;
new getlongAndLat().execute(fullUrl);
textTextView.setText(latitude + "");
//Log.e("TAG", latitude + " " + longitude);
// getLoaderManager().initLoader(LOADER_ID, null, MainActivity.this);
}
});
}
#Override
public android.content.Loader<Weather> onCreateLoader(int id, Bundle args) {
return new WeatherAsyncTaskLoader(this, latitude, longitude);
}
#Override
public void onLoadFinished(android.content.Loader<Weather> loader, Weather data) {
}
#Override
public void onLoaderReset(android.content.Loader<Weather> loader) {
}
public class getlongAndLat extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
Log.e("TAG", connection.getResponseCode() + "");
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
//trouble closing input stream
e.printStackTrace();
}
}
}
extractJsonResponse(jsonResponse);
return null;
}
#Override
protected void onPostExecute(String s) {
latitudeTextView.setText(latitude + "");
longitudeTextView.setText(longitude + "");
super.onPostExecute(s);
}
}
private void extractJsonResponse(String jsonResponse) {
try {
JSONObject rootJsonObject = new JSONObject(jsonResponse);
JSONArray nodeResultsArray = rootJsonObject.getJSONArray("results");
JSONObject nodeFirstObject = nodeResultsArray.getJSONObject(0);
JSONObject nodeGeometryObject = nodeFirstObject.getJSONObject("geometry");
JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");
latitude = nodeLocation.getDouble("lat");
longitude = nodeLocation.getDouble("lng");
} catch (JSONException e) {
e.printStackTrace();
}
}
private String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
}
In your code doInBackground(), you are calling extractJsonResponse() method before return statement. In extractJsonResponse(), you are getting lat and long and setting those to Global variables as mentioned in your code
JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");
latitude = nodeLocation.getDouble("lat");
longitude = nodeLocation.getDouble("lng");
I am sure that you are getting those zero values from Json object. You need to verify this thing at your end

How do i set an ImageView to show an image from an image url?

When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is.
System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}
Here is my Java code
public class HomeActivity extends AppCompatActivity {
//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;
//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
HomeActivity.this.finish();
}
//Initialize view item variables.
loggedUsersName = (TextView)findViewById(R.id.login_user);
successMessage = (TextView)findViewById(R.id.message);
logoutButton = (Button)findViewById(R.id.logoutButton);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
//Get intent and values from the intent started this activity and
//Get loggedIn user values from the LocalDataBase .
Intent intent = getIntent();
String message = intent.getStringExtra("MESSAGE");
firstName = user.mFirstName;
lastName = user.mLastName;
email = user.mEmail;
//Set view values to equal values sent from intent.
loggedUsersName.setText(firstName + " " + lastName);
successMessage.setText(message);
netAsync();
}
//Call this method to execute the Async Task
private void netAsync() {
new NetCheck().execute();
}
//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {
private ProgressDialog mDialog;
//Create and show progress dialog box so user knows the app is trying to login.
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(HomeActivity.this);
mDialog.setTitle("Logging In...");
mDialog.setMessage("connecting to server");
mDialog.setIndeterminate(false);
mDialog.setCancelable(true);
mDialog.show();
}
//Gets current device state and checks for working internet connection by trying Google.
#Override
protected Boolean doInBackground(Object[] objects) {
ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
if ( (myNetInfo != null) && (myNetInfo.isConnected())){
try {
URL url = new URL("http://google.com");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setConnectTimeout(3000);
myConnection.connect();
if (myConnection.getResponseCode() == 200){
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//If successful internet connection start AsyncTask to register user info on server
if(o.equals(true)){
mDialog.dismiss();
new RegisterUser().execute(getProfileImageURL, email);
} else {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
}
}
}
//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
LucasHttpURLConnection.setConnectTimeout(1000 * 6);
LucasHttpURLConnection.setReadTimeout(1000 * 6);
//OutputStream to get response
OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data =
URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String json;
while( (json = bufferedReader.readLine()) != null){
response.append(json + "\n");
break;
}
bufferedReader.close();
IS.close();
LucasHttpURLConnection.disconnect();
return response.toString().trim();
} catch (MalformedInputException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Print server AsyncTask response
System.out.println("Resulted Value: " + result);
//If null Response
if (result != null && !result.equals("")) {
String profilepic = returnParsedJsonObject(result);
new GetBitmapImageFromUrl().execute(profilepic);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
profilePicture.setImageBitmap(profilePicBitmap);
} else {
Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
}
}
//Method to parse json result and get the value of the key "image"
private String returnParsedJsonObject(String result){
JSONObject resultObject = null;
String returnedResult = "";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("image");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
If you are seeing background white instead image. Out of memory exception by using bitmap.
You could use
Option 1
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
Picasso
Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);
I would suggest to go with Piccasso. Since it will handle everything.

Categories

Resources