Android: Internet works in emulator but not on my phone - java

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.

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.

Fixing the NetworkOnMainThreadException without using async codes

I want to have an application use networking operation on its main thread without it throwing a NetworkOnMainThreadException. I don't want to use async codes to get around this. I heard that you can get around the NetworkOnMainThreadException without using async codes by using this code instead, from this answer link: "How to fix 'android.os.NetworkOnMainThreadException'?"
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
The answer stated that you can use this code in the class and it would ignore the NetworkOnMainThreadException and the code would execute without any problems, but when I tried it in my class I got the "identifier expected" error. What am I doing wrong?
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.EditText;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public class myClass {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
public void connect(View v) throws IOException {
Document doc = Jsoup.connect("http://www.google.com//").get();
}
}
}

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

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).

Not able to get audio input for simple microphone app

I am in the process of learning out to use libpd with Android and have ran into a problem. I wanted to see if I could get a simple microphone app working. Just an ~adc -> bpfilter -> *2 -> ~dac. I verified that the patched worked with Pure Data and MobMuPlat.
I wrote over the example program "Circle of Fifths" to make sure libpd was included properly. When I modified it using a tutorial to run my own patch, I was unable to get input from the phone's microphone. The following line seemed to be the issue.
PdAudio.initAudio(sampleRate, inpch, 2, 8, true);
If I have the input channels to 0, the app will open but obviously no sound will come out.This is unless I change the patch to just play a tone and set inpch to 0. When the input channels are set inpch to 1,2, or AudioParameters.suggestInputChannels();the application will not open.
I have also tried small sample rates but I had the same issue. Any ideas?
Here is the full main activity:
/**
*
* #author Peter Brinkmann (peter.brinkmann#gmail.com)
*
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*
*/
package org.puredata.android.fifths;
import java.io.File;
import java.io.IOException;
import org.puredata.android.io.AudioParameters;
import org.puredata.android.io.PdAudio;
import org.puredata.android.utils.PdUiDispatcher;
import org.puredata.core.PdBase;
import org.puredata.core.utils.IoUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioGroup;
import android.widget.Toast;
public class CircleOfFifths extends Activity {
private static final String TAG = "GuitarTuner";
private PdUiDispatcher dispatcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initGui();
try {
initPd();
loadPatch();
} catch (IOException e) {
Log.e(TAG, e.toString());
finish();
}
}
private void initGui() {
setContentView(R.layout.main);
}
private void initPd() throws IOException {
// Configure the audio glue
// int sampleRate = AudioParameters.suggestSampleRate();
int sampleRate = 64;
int inpch = AudioParameters.suggestInputChannels();
PdAudio.initAudio(sampleRate, inpch, 2, 8, true);
// Create and install the dispatcher dispatcher = new PdUiDispatcher();
// PdBase.setReceiver(dispatcher);
}
private void loadPatch() throws IOException {
File dir = getFilesDir();
IoUtils.extractZipResource(getResources().openRawResource(R.raw.patch),
dir, true);
File patchFile = new File(dir, "microphone.pd");
PdBase.openPatch(patchFile.getAbsolutePath());
PdAudio.startAudio(this);
}
#Override
protected void onResume() {
super.onResume();
PdAudio.startAudio(this);
}
#Override
protected void onPause() {
super.onPause();
PdAudio.stopAudio();
}
}
You need a permission for recording audio. Try adding
<uses-permission android:name="android.permission.RECORD_AUDIO" />
to your manifest.

Build failed, wrong class imported?

I am trying to build a very simple Android app, with just instantiating one class, but for some reason it fails and doesn't build, I am probably making some fundamental mistake but am unable to figure out what it is.
package algon.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import anroid.widget.TextView;
import android.graphics.drawable.Drawable;
import android.content.Context;
public class AlgonActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView t = new TextView(Context context);
setContentView(R.layout.main);
}
}
It just doesn't want to instantiate the TextView class, I can't understand why actually.
Thank you for response in advance
TextView t = new TextView(Context context);
should be:
TextView t = new TextView(this);

Categories