I'm new in android.I want to create a weather app that gets data from weather app by api.I write the api code.,but it doesn't work it and it doesn't show in logcat too. I added JsonObject and jsonPart but it doesn't show .First i tried in Log and then device but it doesn't show at all.
public class DownloasTask extends AsyncTask<String,Void,String>{
#Override
at a protected String doInBackground(String... urls) {
String result ="";
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection =(HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data !=1){
char current = (char) data;
result = result +current;
data =reader.read();
}
return result;
}catch (Exception e){
e.printStackTrace();
Log.i("Exception"," url failed");
Toast.makeText(getApplicationContext(),"Could not find the weather",Toast.LENGTH_SHORT).show();
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try{
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
String message ="";
for(int i = 0;i<arr.length();i++){
JSONObject jsonPart =arr.getJSONObject(i);
String main =jsonPart.getString("main");
String description =jsonPart.getString("description");
if(!(main.equals("")) && !description.equals("")){
message +=main +": "+description+"\r\n";
}
Log.i("main",jsonPart.getString("main"));
Log.i("description",jsonPart.getString("description"));
}
if(!message.equals("")){
textView2.setText(message);
}else {
Toast.makeText(getApplicationContext(),"Could not find the weather",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
Log.i("jsonobject", "onPostExecute: ");
Toast.makeText(getApplicationContext(),"Could not find the weather",Toast.LENGTH_SHORT).show();
}
}
}
public void getWeather(View view){
DownloasTask task = new DownloasTask()
task.execute("https://openweathermap.org/data/2.5/forecast?q=" +
editText.getText().toString() +
"&appid=b1b15e88fa797225412429c1c50c122a1");
InputMethodManager inputMethodManager =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(),0);
}
}
Related
public class PerformNetworkTasks extends AsyncTask<String, String, String> {
#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(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<String>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo.toString();
/*
right now I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} 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);
inputDataTV.setText(result);
}
I need to return some data individually. So I need to return an array (i think) so that I can set the TextView as e.g. arrays.get(number).
Is there some other way that I am not realizing here, or should I continue with what I am doing to get the data individually?
Just to add, I am getting the info from a website.
You can return any data type you want
but your AsyncTask structure should be based on result data type
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>/*resultParam*/> {
#Override
protected List<String>/*will same as result parma*/ doInBackground(String... params) {
return null;/*now you can return list of string*/
}
#Override
protected void onPostExecute(List<String>/*finally receive result*/ result) {
super.onPostExecute(result);
}
}
so your code will be
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>> {
#Override
protected List<String> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo;
/*
right now
I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} 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(List<String> result) {
super.onPostExecute(result);
inputDataTV.setText(result.get(0));
}
}
please i am having some issues parsing a list of data form the this link(https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23) i am able to get the data from the json array(articles) but how can i get the data from the josn array(sources)
private void getWebApiData() {
String WebDataUrl = "https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONObject("articles");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is code I am using the get the data of the articles.
To get the sources I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONArray("articles");
JSONObject response3 = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I think I am not getting the code correctly
Here is the second option I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But this only gives me empty text Fields the spaces for the data is populated but it is blank
Please any help will be greatly appreciated
I don't know how your code works. You have tried to get JSONObject as articles which is actually JSONArray. Besides this I don't find any key in your json like sources instead I have found source. To parse source try below way:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("source");
String name = sourceObject.optString("name");
String url = sourceObject.optString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
As Md. Asaduzzaman stated it is actually an JSON array ("articles" to be exact).
I have tested it on my phone and it works no prob. You will have to try and figure out how u want the JSONArray to be parsed thou.
private class AsyncTaskExample extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
stringURL = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) stringURL.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
//render string stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != is) {
is.close();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String js) {
super.onPostExecute(js);
try {
JSONObject jay = new JSONObject (js);
JSONObject source = jay.getJSONObject("articles");
String s = source.getString("title");
System.out.println(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here you will find all you need for JSON.
Best of luck to you :)
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray articles = jsonObject.getJSONArray("articles");
for(int i=0; i<articles.length(); i++){
JSONObject obj1 = (JSONObject) articles.get(i);
JSONObject source = obj1.getJSONObject("source");
Log.i(TAG, "onResponse: " + source.toString()); }
Hope that help you !
I am trying to retrieve json records from the database. On retrieving the GET request over the browser my json responce is of this structure and returning appropriate data
[{"name":"OOGOGOGO","address":"OPOPOPOP","gender":"OPOPOPOP","email":"OPOPOPOP","phonenumber":"OPOPOPOP","nationality":"OPOOPOPO","fk":1}]
I am calling the endpoint url in the assync task doinbackground and this is the endpoint
url = new URL("http://10.0.2.2:88/example/web/app_dev.php/get/1");
the above endpoint returns 405 status code error. On attempting to catch a json exception I get this error
error gotten org.json.JSONException: Value Connection of type java.lang.String cannot be converted
confused on what could be wrong with this endpoint as it returns a 200 ok json response from postman. Kindly assist
Here's the code snippet.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Fetch network data
new NetworkAsyncTask().execute("http://www.mocky.io/v2/591f32f4110000d10307b4c7");
}
private class NetworkAsyncTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(String result) {
if (result != null) {
Log.d("TAG", "Success! Result: " + result);
processResult(result);
} else {
Log.d("TAG", "Failed, no data");
}
}
private void processResult(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
JSONObject nameObject = jsonArray.getJSONObject(0);
String name = nameObject.optString("name");
Log.d("TAG", "name: " + name);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
For more information on networking and JSON on Android, i suggest you read this guide:
https://guides.codepath.com/android/Sending-and-Managing-Network-Requests
https://guides.codepath.com/android/Converting-JSON-to-Models
Hello is have this code on Android Studio:
private class ConsultarrDatos extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("onPostExecute:::::::::::::::::::::::::: " + result);
String strJson= result;
String data = "";
try {
JSONObject jsonRootObject = new JSONObject(strJson);
JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("name").toString();
float salary = Float.parseFloat(jsonObject.optString("salary").toString());
data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
etName.setText(name);
}
} catch (JSONException e) {e.printStackTrace();}
}
}
The thing is, when I recive data from a PHP file the println is printing that:
I/System.out: onPostExecute::::::::::::::::::::::::::
04-03 18:25:50.798 18046-18046/com.example.lorenzo.phpmysql I/System.out: ���
My php code is OK, I don't have any error or things like that!
Do you know why?
Thanks a lot!
This is my downloadUrl
private String downloadUrl(String myurl) throws IOException {
Log.i("URL",""+myurl);
myurl = myurl.replace(" ","%20");
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("respuesta", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
I am trying to implement vtiger's API to connect my android application to it's server. I have added the API to the libs folder and then compile the .jar file. I then use the documentation to connect to the server in java.
boolean result = true;
WSClient client = new WSClient("http://en.vtiger.com/wip");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
result = client.doLogin("username", "Accesskey");
if(!result)
{
System.out.println("Login failed!");
System.out.println(client.lastError());
}
else
{
System.out.println("Login Successful");
}
}
However, I always get the Login failed and no error present. The problem is that when I open the WSClient.java class from inside the .jar, the program states that no sources can be found. I have downloaded these files from http://forge.vtiger.com/frs/?group_id=181&release_id=573 and do not know what to attach as a source. Maybe this is why I cannot connect to the server since I am using the right username and access key supplied by vtiger.
Try this:-
Its an example based on https://demo.vtiger.com/ for login
public class Login extends Activity {
//URL to get JSON Array
private static String url = "https://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin";
//JSON Node Names
private static final String TAG_RESULT = "result";
private static final String TAG_TOKEN = "token";
// contacts JSONArray
JSONArray contacts = null;
String token = null;
String sessionId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new AsyncTask<Void, Void, Void>() {
private ProgressDialog dialog = new ProgressDialog(Login.this);
protected void onPreExecute() {
dialog.setMessage("Loging In... Please wait...");
dialog.show();
}
#SuppressWarnings("unused")
JSONObject result;
#Override
protected Void doInBackground(Void... params) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
result = json.getJSONObject(TAG_RESULT);
JSONObject json_result = json.getJSONObject(TAG_RESULT);
// Storing JSON item in a Variable
token = json_result.getString(TAG_TOKEN);
//Importing TextView
} catch (JSONException e) {
e.printStackTrace();
}
String username="admin";
String accesskeyvalue = "w9OweWKUS4a5sSL";
String accessKey=md5(token + accesskeyvalue);
//For debugging purpose only
//System.out.println(accesskeyvalue);
//System.out.println(token);
//System.out.println(accessKey);
String data = null;
try {
data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("accessKey", "UTF-8") + "="
+ URLEncoder.encode(accessKey, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
//System.out.println(data);
// Send data
try
{
// Defined URL where to send data
URL url = new URL("https://demo.vtiger.com/webservice.php?operation=login");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response
System.out.println(text);
sessionId = text.substring(41, 62);
//System.out.println("doInBackground()"+sessionId);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
}
}.execute();
}
public String md5(String s)
{
MessageDigest digest;
try
{
digest = MessageDigest.getInstance("MD5");
digest.update(s.getBytes(),0,s.length());
String hash = new BigInteger(1, digest.digest()).toString(16);
return hash;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return "";
}
Change the variables as per your need
you don't need to use any additional jar files.