I have 1 EditText 1Button and 1TextView, when I type url in Edittext and click button, the textView will be show the Html from website that i type the url in edittext. I want to get html from web by using url.
Problem
When I using this code in ( AVD Target version 2.3.3). AndroidManifest (minSdkVersion="10" targetSdkVersion="10") and I also change targetSdkVersion="15") both are work correct. but when I change it to run in (AVD target version 4.0.3) it's not work. Y? This is my code
final EditText et = (EditText) findViewById(R.id.editText1);
final Button b = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
URL url = null;
url = new URL(et.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader buff = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line ="";
while((line = buff.readLine())!= null){
tv.append(line);
}
} catch (Exception e) {
}
You're getting a NetworkOnMainThreadException, you can't access the network on the UI thread when using Honeycomb or later. You need to do your work in an AsycnTask. See this question for more info.
//before OnCreate() method
URL url = null;
final TextView tv;
////////
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
url = new URL(et.getText().toString());
new YourAsyncTask.execute();
}
} catch (Exception e) {
}
//after onCreate() method
class YourAsyncTask extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
//show your dialog here
progressDialog = ProgressDialog.show(YourActivity.this,"Please wait...", "Loading ...", true);
}
#Override
protected Void doInBackground(Void... params)
{
//make your request here - it will run in a different thread
try
{
URLConnection conn = url.openConnection();
BufferedReader buff = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line ="";
while((line = buff.readLine())!= null){
tv.append(line);
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
try
{
progressDialog.dismiss();
///Show your Data here
}
catch (Exception e)
{
// TODO: handle exception
}
}
}
Check INTERNET PERMISSION in Menifest.
Related
This is my main activity which gets a json array from a URL. My problem is that when I try and Unit test what should be in the textview it gives me a null pointer exeption.
public class MainActivity extends AppCompatActivity {
TextView txtJson;
ProgressDialog pd;
public static TextView testString;
String jsonString = null;
List<Location> locations;`enter code here`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
testString = (TextView) findViewById(R.id.test_for_string);
new JsonTask().execute("https://wsu-dining-service.s3.amazonaws.com/current-menu.json");
}
protected void postCreate()
{
mapStrinToClass();
testString.setText(locations.get(0).getName());
}
private void mapStrinToClass()
{
ObjectMapper objectMapper = new ObjectMapper();
JsonFactory jsonFactory = objectMapper.getFactory();
try {
JsonParser jsonParser = jsonFactory.createParser(jsonString);
locations = objectMapper.readValue(jsonString,
new TypeReference<List<Location>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
}
private 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); //here u ll get whole response...... :-)
}
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();
}
jsonString = result;
postCreate();
}
}
}
My unit test
* When I run the app the textview is populated with "Tim & Jeanne's Dining Commons" but the test fails and says the testString.getText().toString(); is null
#Test
public void isMenuCorrect() {
String menuTxt = MainActivity.testString.getText().toString();
assert(menuTxt == "Tim & Jeanne's Dining Commons");
}
First of all, you should use Espresso to run UI tests, under the androidTest folder. Example:
onView(allOf(withId(R.id.tvJsonItem), withText("Tim & Jeanne's Dining Commons")).check(matches(isDisplayed()));
Basically what we're doing here is checking if a view with id R.id.tvJsonItem and with a text "Tim & Jeanne's Dining Commons" is displayed on the screen. Now how to run Espresso tests is not in this question's scope.
Second, your production code should never know what's going on in the tests, like you have created a TextView just to be used in your unit tests.
Finally, never have static references to your views since you can't guarantee your activity has been created by the time you try to access them. In fact, a view should only be seen by its parent. In your case, the reference TextView should be private in your activity.
I'm following this tutorial about Rest API in android. I did everything what was in this video and I'm not getting any data, aslo I've changed the link as shown in but I'm not getting any data. Here is my code:
public class MainActivity extends AppCompatActivity {
private TextView value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value = (TextView) findViewById(R.id.textView);
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
}
});
}
public class JSONTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(urls[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);
}
// to bedzie wyswietlone
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parrentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parrentArray.getJSONObject(0);
String movieName = finalObject.getString("movie");
int movieYear = finalObject.getInt("year");
return movieName;
}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);
value.setText(result);
}
}
}
I'm beginner in android, please don't say that I should start with something easier. I'm doing it for my Django project, I want to create mobile app for it. Thanks a lot for help!
Hiiii, i have checked your code and there is a issue because "https" connection.
You can use Volley library for that. Use below code for get response from yout api link.
Firstly add compile ‘com.mcxiaoke.volley:library-aar:1.0.0’ in yout build.gradle file.
now add below code in your activity
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, "https://jsonparsingdemo-
cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt", null, new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, ""+response,
Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue =
Volley.newRequestQueue(getApplicationContext());
requestQueue.add(jsonObjectRequest);
I am currently working on an android project, and I want to be able to press a button and it will display user data into a listview on another activity. I currently have it working in a sense however it requires me to press two buttons. One gets the json data from the mysql database, and the other then sends it in an intent to the next activity allowing me to display it.
I was hoping there would be a way where both of these methods could be run by one button click, or else have both in one method.
public class MyMainActivity extends AppCompatActivity {
String url = "http://192.168.20.120";
String json_string;
View v;
//Button to get the data
ImageButton getUserDetailsBtn;
//Button to parse the data
ImageButton parseUserDetailsBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_main);
getUserDetailsBtn= (ImageButton)findViewById(R.id.getUserDetailsButton);
parseUserDetailsBtn = (ImageButton)findViewById(R.id.parseUserDetailsButton);
getUserDetailsBtn.setVisibility(View.GONE);
}
//
//get user details in app
//
public void getDetails(View view) {
new LoadUserDetails().execute();
parseUserDetailsBtn .setVisibility(View.GONE);
getUserDetailsBtn= .setVisibility(View.VISIBLE);
}
//Load the user details
class LoadUserDetails extends AsyncTask<Void,Void,String>
{
String json_url;
String JSON_STRING;
#Override
protected void onPreExecute() {
json_url = url+"/getUserDetails.php";
}
#Override
protected String doInBackground(Void... voids){
try{
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while((JSON_STRING = bufferedReader.readLine())!=null)
{
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedJsonException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textview = (TextView) findViewById(R.id.textview);
textview.setText("");
json_string = result;
}
}
//
//parse the data
//
public void parseJSON(View view)
{
if(json_string==null){
Toast.makeText(getApplicationContext(), "First get JSON Data", Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(this, ShowUserActivity.class);
intent.putExtra("json_data", json_string);
startActivity(intent);
}
}
Start your Activity from onPostExecute because onPostExecute gets executed on UI thread
#Override
protected void onPostExecute(String result) {
TextView textview = (TextView) findViewById(R.id.textview);
textview.setText("");
json_string = result;
if(json_string==null){
Toast.makeText(getApplicationContext(), "First get JSON Data", Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(MyMainActivity.this, ShowUserActivity.class);
// and change this to MyMainActivity.this
// this will point to your task instead of Activity
intent.putExtra("json_data", json_string);
startActivity(intent);
}
}
I am trying to create a native login screen, where the username and password boxes slide off the screen while the request is being processed (and slide back up if the login is unsuccessful).
In order to achieve that, I have defined my animation (DropDownAnimation) and I assign it to my LinearLayout (footer). When the user clicks the Login button, I start the animation, and then call a function (tryLogin()) which starts an AsyncTask. The AsyncTask handles all the work of creating and sending the login request, and getting the JSONObject response.
However, my problem is that the slideDown animation doesn't start until after the AsyncTask has completed. This doesn't look so bad on a successful login, but on a failed login it means that the LinearLayout never slides down - it jumps to the bottom of the screen, to begin the slideUp animation back to its original position.
This seems like a similar problem to this question, but I'm not doing using bindService() and all my non-UI code seems (to me) to be contained in the AsyncTask already. LogCat tells me:
06-24 04:37:35.141: I/Choreographer(5347): Skipped 137 frames! The application may be doing too much work on its main thread.
I assume those are the frames where the footer would be sliding down - but I can't figure out where it is that I'm executing things on the main thread. Here's my code for LoginPage and LoginTask.
LoginPage.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
login = (Button) findViewById(R.id.login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
footer = (LinearLayout) findViewById(R.id.footer);
// We must wait for the layout to be finalised before trying to find heights.
ViewTreeObserver vto = footer.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
initAnimations();
}
});
loading = (TextView) findViewById(R.id.loading);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
// Neither of these two things happen until after LoginTask is done.
footer.startAnimation(slideDown);
loading.setVisibility(TextView.VISIBLE);
tryLogin(mUsername, mPassword);
}
});
}
protected void tryLogin(String mUsername, String mPassword) {
Exception e;
String loginUrl = getString(R.string.login_url);
String clientId = getString(R.string.client_id);
String clientSecret = getString(R.string.client_secret);
LoginTask loginTask = (LoginTask) new LoginTask().execute(mUsername, mPassword, loginUrl, clientId, clientSecret);
if ((e = loginTask.getException()) != null) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
} else {
JSONObject response;
try {
response = loginTask.get();
Log.d("login", response.toString());
if (!response.has("access_token")) {
loading.setVisibility(TextView.INVISIBLE);
footer.startAnimation(slideUp);
Toast.makeText(this, "Login error", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(this, FullscreenWebView.class);
i.putExtra("accessToken", response.get("access_token").toString());
startActivity(i);
overridePendingTransition(0, 0);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
Thread.currentThread().interrupt();
} catch (ExecutionException e1) {
e1.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
throw new RuntimeException(e);
}
}
}
LoginTask.java
class LoginTask extends AsyncTask<String, Void, JSONObject> {
private Exception exception;
#Override
protected JSONObject doInBackground(String... params) {
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
JSONObject response = null;
String parameters = "grant_type=password&username="+params[0]+"&password="+params[1]+"&client_id="+params[3]+"&client_secret="+params[4];
try {
url = new URL(params[2]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
// username or password is probably wrong
Log.d("login", ""+connection.getResponseCode());
if (connection.getResponseCode() != 200) {
return new JSONObject();
}
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("login", sb.toString());
response = new JSONObject(sb.toString());
isr.close();
reader.close();
} catch (Exception e) {
this.exception = e;
}
return response;
}
}
I've also tried making LoginTask be a member class of LoginPage, and starting the animation in the onPreExecute() method, but that didn't change anything.
Any help is much appreciated!
When you use AsyncTask.get(), you are blocking the UI thread. As the animation runs on the UI thread, it appears as if it is not running (while in fact it is blocked by your long running tryLogin method).
Instead, you should move the code that relies on the result from the LoginTask to its onPostExecute method:
protected void tryLogin(String mUsername, String mPassword) {
String loginUrl = getString(R.string.login_url);
String clientId = getString(R.string.client_id);
String clientSecret = getString(R.string.client_secret);
new LoginTask().execute(mUsername, mPassword,
loginUrl, clientId, clientSecret);
}
LoginTask.java
class LoginTask extends AsyncTask<String, Void, JSONObject> {
private Exception exception;
#Override
protected JSONObject doInBackground(String... params) {
// Unchanged
}
public void onPostExecute(JSONObject response) {
if (exception != null) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
} else {
Log.d("login", response.toString());
if (!response.has("access_token")) {
loading.setVisibility(TextView.INVISIBLE);
footer.startAnimation(slideUp);
Toast.makeText(this, "Login error", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(this, FullscreenWebView.class);
i.putExtra("accessToken", response.get("access_token").toString());
startActivity(i);
overridePendingTransition(0, 0);
}
}
}
}
the following is my code. Editor: Eclipse, Platform: Windows.
Its a chat application where 2 android emulators connect through a tcp socket.
UI consists of a send button, a text view and a text box.
Problem: As soon as I type text and hit send, the application crashes.
server port is 8000.
So my redirection is redir add tcp:8081:8000 and redir add tcp:8082:8000.
I donno what is wrong in my code. Please suggest me somthing I need to change.
public class HelloandroidActivity extends Activity
{
/** Called when the activity is first created. */
public int serverport=8000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText nameField = (EditText) findViewById(R.id.editText1);
final Button button2 = (Button) findViewById(R.id.button1);
Integer severport=8000;
new Server().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,severport);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final String name = nameField.getText().toString();
final TextView tv = (TextView) findViewById(R.id.textView1);
//tv.setText(name);
String s=null;
new Client().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,s);
}
});// end onclicklis
}//end oncreate
class Server extends AsyncTask <Integer, String, String>
{
public InetAddress byIpAsName ;
int r=0;
#Override
protected String doInBackground(Integer... serverport) {
//i[0]=serverport;
Integer[] sp=serverport;
BufferedReader in=null;
ServerSocket s=null;
r=sp[0];
String cIn="";
try {
//byIpAsName = InetAddress.getByName("10.2.2.15");
s=new ServerSocket(r);
while(true)
{
Socket client = s.accept();
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line=in.readLine();
cIn=null;
while(line!=null){cIn=cIn.concat(line);}
}//while
} catch (IOException e) {
e.printStackTrace();
}
try {
s.close();
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
return cIn;
}//end inBackground
//#SuppressWarnings("null")
protected void onPostExecute(String... cIn)
{
}//onpost execute
}//server class
public class Client extends AsyncTask<String, String, String>
{
PrintWriter out = null;
BufferedReader in=null;
String sIn=null;
//Server s1=new Server();
//int q=s1.r;
TelephonyManager tel = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() - 4);
int q = Integer.parseInt(portStr);
Socket socket;
#Override
protected String doInBackground(String... params) {
try
{
//q=8080;
InetAddress byIpAsName1=InetAddress.getByName("10.0.2.2");
socket = new Socket(byIpAsName1, q);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line=in.readLine();
sIn=null;
while(line!=null){sIn=sIn.concat(line);}
}
catch (IOException e) {
e.printStackTrace();
}//catch
return sIn;
}//in background
protected void onPostExecute(String... sIn)
{
String c=null;
final TextView tv = (TextView) findViewById(R.id.textView1);
c=c.concat(sIn[0]);
tv.setText(c);
}
}
}//main class
From your logcat, what is important is this line:
03-16 23:12:23.434: E/AndroidRuntime(571): java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10040 nor current process has android.permission.READ_PHONE_STATE.
This indicates that in order to run your code, you need the READ_PHONE_STATE permission in the android manifest.xml.
Add this line to the manifest, outside of the <application> tag but inside the <manifest> tag.
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
If this does not solve the issue, the problem could be related to this answer.