Not able to read a specific JSON url using socket in Android - java

I want to read a Json URL using sockets and display it in a textbox.
When I use URLs other than my given URL, it shows the output file. But its not the same case with my URL. The content in the URL is very large (around 184,523 characters).
Here is the code that I am using:
public class MainActivity extends Activity {
URLConnection feedUrl = null;
String json="";
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void, Void, Void>(){
#Override
protected void onPreExecute() {
txt=(TextView)findViewById(R.id.myresponse);
txt.setText("intialize");
}
#Override
protected Void doInBackground(Void... params) {
URLConnection feedUrl;
try {
feedUrl = new URL("http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week").openConnection();
InputStream is = feedUrl.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
json= sb.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
txt.setText(json);
}
}.execute();
}
}
The URL is http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week. Please can someone tell why it is not running?
One more question: What should I do if I want to print only a specified object of the JSON file.
For example, if I want to print the entire 5th object instead of the whole file. What should I do in that case?

First you have to format the result so you can get the actual JSON:
Matcher matcher = Pattern.compile(Pattern.quote("callback(") + "(.*?)" + Pattern.quote(");")).matcher(json);
while (matcher.find())
json = matcher.group(1);
After you get the formated json you need to transform it into a JSONObject
try{
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("features"); //get the features array
JSONObject myObject= array.getJSONObject(5); //get the element 5
}catch(Exception e){
e.printStackTrace();
}
Now you have a jsonobject called myObject with the 5th feature.

Related

how to get data from url in android studio

I want to get data from url and show in a textView , But after receiving, it only shows html codes.
I use a Educational video but my result is wrong.
I used another methods too but all result are same and just show html codes.
MainActivity :
public static final String SAMPLE_URL = "http://nimatest.epizy.com/ffff.json";
findViewById(R.id.btn_get_data).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskGetData().execute(SAMPLE_URL);
}
});
public class TaskGetData extends AsyncTask<String , String , String>{
#Override
protected void onPreExecute() {
textView.append("Get data ...\n\n");
}
#Override
protected String doInBackground(String... params) {
return MyHttpUtils.getDataHttpUriConnection(params[0]);
}
#Override
protected void onPostExecute(String result) {
textView.append(result + "\n");
}
}
MyHttpUtils :
public static String getDataHttpUriConnection(String uri){
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String result = inputStreamToString(con.getInputStream());
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String inputStreamToString(InputStream stream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = "";
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line);
sb.append("\n");
}
return sb.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
Your code is fine. It reads HTML from a URL
This site requires Javascript to work
HttpUrlConnection does not use or render dynamic Javascript created web pages, only static html content
Try a different endpoint for JSON data...
Also, please look into using a proper HTTP library for Android rather than using AsyncTask like Okhttp or Volley

Value Connection of type java.lang.String cannot be converted to JSONObject in getting objects from the database

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

How to save the value of json response in shared preference?

I have to hit a json service and if the response came true than I have to save the user value in shared preference for future use. How can i do that?
my url is:
http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id={aff_id}
Variables will be passed by the sdk user. In the above url my variables are- id: 4 and public_key: 9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G
I have made a class and declared a static method. Inside the static method I have to do parsing and save the variables in shared preference.
public class InitializeSDK {
public static void init(final Context ctx, int id, String public_key){
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... unused) {
return null;
}
protected void onPostExecute(Void unused) {
}
}.execute();
}
}
Please tell me how to parse it to get the response and save it in shared preference?
Here is a sample code you can use:
protected Void doInBackground(Void... unused) {
//TODO: add code to read http request and store the json data in json variable
JSONObject jsonObject = new JSONObject(json);
boolean state = jsonObject.getBoolean("success");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putBoolean("state",state);
editor.commit();
return null;
}
Firstly, I suggest you need to get JSON data as a string and you can parse it.
String json = "";
URL url;
HttpURLConnection connection = null;
try {
url = new URL("http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id=");
connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char currentChar = (char) data;
data = reader.read();
json += currentChar;
}
}catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return json;
}
I call this method inside the doInBackground.

Send data from android to website but no result returned

I am totally new in java and android.. I am sure I did it wrong on the code, please help me fix it
I try to send the content of a tweet as a String from an android application to this online parser: http://demo.ark.cs.cmu.edu/parse, and I want to retrieve the result of the parsing, here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
String Tobetag = urlEncode(contentTweet);
new Analyser().execute();
}
private String urlEncode(String s){
try {
return URLEncoder.encode(s,"UTF-8").replace("+", "%20");
}
catch ( UnsupportedEncodingException e) {
throw new RuntimeException(s,e);
}
}
private class Analyser extends AsyncTask<Integer, Integer, Integer>
{
private String mUrl = "http://demo.ark.cs.cmu.edu/parse?sentence=";
#Override
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
try
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(mUrl + mTobetag));
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
String result = reader.readLine();
System.out.println("Top");
System.out.println(result);
System.out.println("Bottom");
in.close();
}
catch(Exception e)
{
Log.e("Twitter", "doInBackground_" + e.toString());
}
return new Integer(1);
}
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected void onPostExecute(Integer i) {
}
}
I ran the code, no error reported but I didn't get the parse result, I only have this:
What can I do to get the result I wanted?
P.S. Also I am not sure I used the urlencoder right, it turn the slashes of the tweet content into %2F, but when I use the online parser by a browser, it shows that it doesn't change the slashed at all, please help
You are reading only the first line of the response, if you want to read the entire response you can do it like this:
String result = "";
for(String line;(line=br.readLine())!=null;){
result += line;
}
This will get you the entire http://demo.ark.cs.cmu.edu/parse page as a response, if you want the response to be only a JSON object, use this URL instead http://demo.ark.cs.cmu.edu/parse/api/v1/parse?sentence=....

Cannot connect to vtiger database

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.

Categories

Resources