java.net.MalformedURLException in android while accessing asp.net Web API - java

I've seen this question, it's not my case, since I don't have backslashes in my url,
I have simple URL like, https://url.com/login
My Code,
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class LoginActivity extends AppCompatActivity {
URL url = new URL("https://url.net/login/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.submitbtn);
EditText edtxt = (EditText) findViewById(R.id.usernm);
EditText edtxt2 = (EditText) findViewById(R.id.usrpwd);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(i);
}
});
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
}
}
Screen shot:
When I hover on new URL();, I get error as:
Unhandled Exception: java.net.MalformedURLException
That's why I'm getting another error at line,
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
in stack Trace I'm getting error as,
Error:(48, 13) error: cannot find symbol method readStream(InputStream)

When I hover on new URL();, I get error as:
The URL() constructor throws java.net.MalformedURLException. You need to wrap that constructor call in a try/catch block.
That's why I'm getting another error at line,
That is because getInputStream() also throws checked exceptions. You need to wrap that code in a try/catch block.
That's the line of error and I'm getting error as Error:(48, 13) error: cannot find symbol method readStream(InputStream)
That is because you did not implement a method named readStream() on this class.
All of this is covered in any decent book or course on Java programming.
Eventually, once you get past these compile errors, your code will crash at runtime with a NetworkOnMainThreadException, as you cannot perform network I/O on the main application thread. You will need to move this HTTP code to a background thread, either one that you create yourself or by using an HTTP client API that can handle it for you (e.g., OkHttp).

Related

Android giving error while accessing json data from the internet

I am a beginner, building a goofy app that uses an online API. I uploaded the .json file to GitHub, from where my app accesses it and gives the output. However, it always runs the statements for onErrorResponse. Am I doing something wrong?
Here's the code for MainActivity:
package com.example.jsonparsing;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DownloadManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
Button search;
EditText input;
TextView word;
TextView meaning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = findViewById(R.id.button_getMeaning);
input = findViewById(R.id.editText_input);
word = findViewById(R.id.textView_word);
meaning = findViewById(R.id.textView_meaning);
requestQueue = Volley.newRequestQueue(this);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String term = input.getText().toString().toLowerCase();
String displayInput = term.toUpperCase() + ":";
word.setText(displayInput);
JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, "https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String definition = response.getString(term);
meaning.setText(definition);
} catch (JSONException e) {
e.printStackTrace();
meaning.setText("Sorry, this word doesn't exist in the boner database.");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Connection error, please check internet connection.", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest1);
}
});
}
}
The project uses Volley and I have added Internet permission in the manifest.
Edit: here's the .json :
https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json
The json url you have posted is a link to someone's github page with the json, but not the json itself. Whats most likely happening is volley is downloading the HTML page in its entirety which contains the json. Its then complaining that its not correctly formatted json.
If you want that json directly you need to find a way to host it somewhere. For example github has an api that you can access json files like this https://api.github.com/users/mralexgray/repos
For local testing you could always copy it into a local json file and import into the res/raw of your app and reference it from there.

Unable to properly parse json file

I'm working on a random quote app, and I need to parse ajson file through an http connection. I'm succesfully stablishing the connection; and fetching json data, but when I try parsing it, it seems I'm getting the keys, value, or object not mapped correctly. Or maybe I'm not using the correct code. Any help appreciated. Thanks
package com.example.george.radonquote;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
Toolbar myToolbar;
String randQuote;
String author;
TextView quoteTextView;
ImageView bgImageView;
ImageView nextImageView;
String url = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting the ActionBar for the activity
myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
quoteTextView = (TextView) findViewById(R.id.quote_text);
nextImageView = (ImageView) findViewById(R.id.next_quote);
/*onclick listener for next quote*/
nextImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FetchQuote fetchQuote = new FetchQuote();
fetchQuote.execute();
}
});
}
/*
* async class to get random quote in background
*/
class FetchQuote extends AsyncTask<Void, Void, Void> {
String quote = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Fetching Quote!",Toast.LENGTH_LONG).show();
}
/*
* making connection and parsing json data
*/
#Override
protected Void doInBackground(Void... voids) {
try {
URL uri = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null) {
Log.v("line: ",line);
line = bf.readLine();
quote += line;
}
}
catch (MalformedURLException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
try {
JSONArray ja = new JSONArray(quote);
JSONObject jo = (JSONObject) ja.get(0);
randQuote = jo.get("content").toString().replaceAll("\\<[^>]*>","");
author = jo.get("title").toString();
Log.v("QUOTE", randQuote+" "+author);
}
catch (JSONException ex){
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
// Log.v("Post Exec", randQuote);
quoteTextView.setText(randQuote);
}
}
}
You are not getting a valid json from the url. First rectify your string then parse the json . try below code. This is only a temporary solution.
try {
String requiredString = quote.substring(quote.indexOf("(") + 1, quote.indexOf(")"));
JSONArray ja = new JSONArray(requiredString );
JSONObject jo = (JSONObject) ja.get(0);
randQuote = jo.get("content").toString().replaceAll("\\<[^>]*>","");
author = jo.get("title").toString();
Log.v("QUOTE", randQuote+" "+author);
}
The problem is the _jsonp=mycallback parameter in the url. Using this parameter is causing malformed JSON to be returned to you.
As you can see in the documentation, the JSONP parameter is used in JavaScript in order to execute a callback.
Since you're using Java in an Android app, there is no need to specify a callback.
All you need to do is modify the url so that it doesn't define a callback:
String url = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
Then, the response will be valid formatted JSON, for example:
[
{
"ID":1572,
"title":"Si Scott",
"content":"<p>I really like looking at design and thinking: that attention to detail must have taken absolutely ages.<\/p>\n",
"link":"https:\/\/quotesondesign.com\/si-scott\/",
"custom_meta":{
"Source":"<a href=\"http:\/\/www.formatmag.com\/art\/si-scott\/\">article<\/a>"
}
}
]
Then, your existing code should work. I just tested it, and it logged the correct response:
10-06 12:35:52.522 4606-4624/com.example.ex V/QUOTE: Graphic designers find themselves in a role of visual dishwashers for the Information Architects’ chefs.
Gunnar Swanson
Use JSOUP library and follow the given code
String content;
content = Jsoup.parse(content).text();

Unknown pattern character 'X' Exception occurs connecting to IBM Watson conversation API from Android

I am working with some chat bot application on Android. Everything was working perfect before. But the same application that worked before, now shows an error. "Unknown pattern character 'X' " . Don't know what i did wrong. I tried a lot to find the bug but failed. I am attaching my code here..
package com.example.rove2.conversation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.ibm.watson.developer_cloud.conversation.v1.ConversationService;
import com.ibm.watson.developer_cloud.conversation.v1.model.MessageRequest;
import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
String conversation_username;
String conversation_password;
String workspace_id;
Button sendbtn,clearbtn,jsonbtn;
EditText input,json;
String JsonString="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conversation_username = "c9d2fd27-0868-4e56-b3ae-66b76d2b52b4";
conversation_password = "DYLntDWRvf12";
workspace_id="cbb7fc4d-c216-4a81-ae70-445d6fa9dab9";
sendbtn=(Button)findViewById(R.id.button);
clearbtn=(Button)findViewById(R.id.button2);
input = (EditText)findViewById(R.id.editText);
json =(EditText)findViewById(R.id.editText2);
jsonbtn=(Button)findViewById(R.id.button3);
}
String sendtoWatson(String message)
{
ConversationService service = new
ConversationService(ConversationService.VERSION_DATE_2017_02_03);
service.setUsernameAndPassword(conversation_username,
conversation_password);
MessageRequest newMessage = new
MessageRequest.Builder().inputText(message).build();
MessageResponse response = service.message(workspace_id,
newMessage).execute();
String tx = response.toString();
return tx;
}
public void send(View view){
Thread t=new Thread(){
public void run() {
String text = input.getText().toString();
final String result = sendtoWatson(text);
JsonString = result;
runOnUiThread(new Runnable() {
#Override
public void run() {
try{
JSONObject reader = new JSONObject(result);
JSONObject output = reader.getJSONObject("output");
JSONArray Intent = output.getJSONArray("text");
String speechTxt=Intent.getString(0);
json.setText(speechTxt);
}
catch (JSONException e) {
e.printStackTrace();
}
}
});
}};
t.start();
}
public void clearbutn(View view){
input.setText("");
json.setText("");
}
public void jsonbtn(View view){
json.setText(JsonString);
}
}
The error occurs at the line
MessageResponse response=service.message(workspace_id,newMessage).execute();
I could find an answer for a similar issue here BlueMix service error with Android app - 'Unknown pattern character 'X''
But i am not able to understand the solution my android studio version is 2.1.2 and JDK version is 8. Please help...
This is a known issue that was fixed But not released to maven yet. If you look at the README in the repository, there are instructions on how to use the snapshot release while we wait for 3.8.1.

Fatal Exception main at onclick

Im getting E/AndroidRuntime: FATAL EXCEPTION: main at com.test.megatest.Main4Activity$1.onClick(Main4Activity.java:37).
Ive read tons of posts on this forum but I cant figure out what Im missing,
This is the Main4Activity.java:
package com.test.megatest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main4Activity extends AppCompatActivity {
EditText inputText;
TextView response;
Button saveButton, readButton;
private String filename = "SampleFile.txt";
private String filepath ="MyFileStorage";
File myExternalFile;
String myData ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
inputText = (EditText) findViewById(R.id.myInputText);
response = (TextView) findViewById(R.id.response);
saveButton =(Button) findViewById(R.id.saveExternalStorage);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fos = new FileOutputStream(myExternalFile); //LINE 37
fos.write(inputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText("");
response.setText("SampleFile.txt saved to somewhere..");
}
});
}
}
Can someone here just point me in the right direction? :)
The file you try to open an output stream for is NULL.
You declared it as a member but never initialized it.
Initialize file as
File myExternalFile=new File("SampleFile.txt");
Your Main4Activity has a "File" variable:
File myExternalFile;
But without assigning any object/value to that variable You are trying to use it in:
FileOutputStream fos = new FileOutputStream(myExternalFile);
Obviously you will get an Exception for that :P
You should initialise "myExternalFile" using any of the 4 public constructors specified at java.io.File (depending on your use case).
For example:
// If you need a "Persistent" file in private directory of your application
//
myExternalFile = new File(this.getFilesDir() ,"name_of_your_file.txt");
//
// or
// If you need a "Cache" file
myExternalFile = new File(this.getCacheDir() ,"name_of_your_file.txt");
Locations of above files on your Android filesystem is:
# Persistent: /data/data/com.test.megatest/files or
(Any File Manager App) /Android/data/com.test.megatest/files
# Cache: /data/data/com.test.megatest/cache or
(Any File Manager App) /Android/data/com.test.megatest/files
Reference:
1) java.io.FileOutputStream -> FileOutputStream (File file) public constructor
"Creates a file output stream to write to the file represented by the specified File object"

Android: Internet works in emulator but not on my phone

I'm making an app which reads a certain part of a website and posts it to the screen. The app currently works in my android emulator but when I transfer it to my galaxy S2, it doesn't seem to access the website at all.
package com.example.beam;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
String current = null;
Button check;
TextView text;
TextView url;
String[] lines = new String[12];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check = (Button) findViewById(R.id.checkstatus);
text = (TextView) findViewById(R.id.textView1);
url = (TextView) findViewById(R.id.url);
String[] lines = new String[12];
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// Attempt to the read the source from a website.
String bodyHtml = "null";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.spring8.or.jp/ext/ja/status/text.html");
ResponseHandler<String> resHandler = new BasicResponseHandler();
try {
bodyHtml = httpClient.execute(httpGet, resHandler);
} catch (Exception e) {
e.printStackTrace();
}
double current = 0;
try{
String derp = bodyHtml.substring(bodyHtml.lastIndexOf("mA") - 5, bodyHtml.lastIndexOf("mA"));
current = Double.parseDouble(derp);
}
catch(Exception e){
}
url.setText(current + " mA");
}
});
}
}
Apologies if the coding is a bit poor and messy, I'm quite new to all this. How do I fix this issue? Thank you
Also, I'm pretty sure I've set the permission correctly in the manifest.
Try this....
Its a good practice to Keep the UI work on UI thread and Non-UI work on Non-UI thread, but that became a LAW from the release of HONEYCOMB Android version.... That may be causing the error.
So you can do the following....
Do the Http on a separate thread, and then place the value on the UI using Handler, Handler Keep the reference of the thread in which it was created.
You can use AsyncTask which is specially designed for android to make a sync between
UI and Non-UI thread.
Note:
Please check the Internet Permission in AndroidManifest, though i know you have done it, cause the app ran on the emulator.... but still..no harm in checking it again.

Categories