How to get data from remote php website in android application - java

I want to get data from php remote website.I have a php file through which i want to import data in android application.
I am unable to get data...exception error occurred(only exception part is running).I am new with the android so Please help me to solve this problem.I shall be thankful to you.Impatiently waiting for help.Thanks in advance.Stay blessed....
Here is my code.
package com.example.androiddevelopers.my;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
public class Downloadweb extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
String data = "";
URL url ;
HttpURLConnection urlConnection = null;
try{
String postdata = URLEncoder.encode("Player Name","UTF-8")+"=" + URLEncoder.encode(params[1],"UTF-8");
postdata += URLEncoder.encode("Player Role","UTF-8")+"=" + URLEncoder.encode(params[2],"UTF-8");
//url =new URL("http://localhost/ODI-Team/ODI.php");
url = new URL(params[0]);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(postdata);
wr.flush();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int ch = reader.read();
while(ch != -1){
char current=(char)ch;
data += current;
ch=reader.read();
}
return data;
}
catch (Exception e){
//Toast.makeText(MainActivity.this, "error occured"+e.getMessage(), Toast.LENGTH_SHORT).show();
return "Error ocured"+e.getMessage();
}
}
#Override
protected void onPostExecute(String s){
try{
webView.loadData(s,"text/html","UTF-8");
}
catch (Exception e){
Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView=(WebView)findViewById(R.id.webView);
try{
Downloadweb downloadweb=new Downloadweb();
//replace with your own laptop ip address
downloadweb.execute(new String[]{"http://192.168.0.109/ODI.php"});
}
catch (Exception e){
//Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
webView.loadData("<html><body>Error Occured.</body></html>","text/html","UTF-8");
}
}
}

Man, protected String doInBackground(String... params) - this method perform operations on a background thread. String... params - it's a string array with parameters, which you'll passing to the this thread. .execute() - here you are executing asynctask with parameters passed to the background thread, but there is only one argument "http://192.168.0.109/ODI.php", but in your doInBackground() method you are trying to get "Player Name" and Player Role from argument, which doesn't exist. Here you have what I mean.
protected String doInBackground(String... params) { // <--- in yor case params contains only 1 element with index 0
...
String postdata = URLEncoder.encode("Player Name", "UTF-8") + "=" + URLEncoder.encode(params[1], "UTF-8"); // here's your second execute params, it's error
postdata += URLEncoder.encode("Player Role", "UTF-8") + "=" + URLEncoder.encode(params[2], "UTF-8"); // here's your third execute params, it's error
url = new URL(params[0]); // here's your first execute params
}
And in activty
Downloadweb downloadweb = new Downloadweb();
//replace with your own laptop ip address
downloadweb.execute(new String[] {
"http://192.168.0.109/ODI.php", // <--- its params[0]
"", // <--- here's your missing params[1]
"" // <--- here's your missing params[2]
});
That's all, why you are getting an error.
Here's you have some docs, how using asynctask with examples.
#Edit
I'm using BufferedReader for fetching string from remote server
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = rd.readLine()) != null) {
response.append(line + '\n');
}
rd.close();
return response.toString();

Related

Java getter and setter issue

When setting a value in setData the value is OK in String returnDataTab1, but when getId() states it's null. Is the issue staring me in the face.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String,Void,String>
{
Context context;
String dataResponse = "";
String returnDataTab1;
//getter
public String getId()
{
//The system out below shows a value of null although the setData method set it ok.
System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz : "+returnDataTab1);
return returnDataTab1;
}
public void setData(String newResult)
{
returnDataTab1=newResult;
System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz : "+returnDataTab1);
/// the returnDataTab value is set ok
}
BackgroundTask(Context ctx)
{
this.context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String urlLogin = "";
String task = params[0];
String loginusername="";
String loginpassword="";
if (task.equals("login"))
{
urlLogin = "http://domain/LoginAndRegister-login.php";
loginusername = params[1];
loginpassword = params[2];
//
try
{
URL url = new URL(urlLogin);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//send the driver number to the database
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myDatalogin = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginusername,"UTF-8")
+"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginpassword,"UTF-8");
bufferedWriter.flush();
bufferedWriter.write(myDatalogin);
bufferedWriter.close();
outputStream.close();
//get response from the database
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//String dataResponse = "";
String inputLine = "";
while((inputLine = bufferedReader.readLine()) != null)
{
dataResponse += inputLine;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return dataResponse;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}//end if statement
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
/// gets value OK from background task
#Override
protected void onPostExecute(String result)
{
this.setData(result);
}
}
Would appreciate if you guys could take a look and point out the obvious mistake.
This is the code called from a tab
BackgroundTask backgroundTaskLogin = new BackgroundTask(Tab1Activity.this);
backgroundTaskLogin.execute(task,username,password);
String x;
x=backgroundTaskLogin.getId();
Toast.makeText(getApplicationContext(), "Data Response : "+x, Toast.LENGTH_SHORT).show();
The values are set from
protected void onPostExecute(String result)
{
this.setData(result);
// gets result value fine
}

How to start new activity after login success in Android?

I need to start new activity after login success. I don't know the code for starting activity from one to another and how to do it in this code below, i have code for that thing is here, in these it is code for background workers.java and we have two panel :
package com.example.androidphp2016;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url1="http://adminlogin.php";
String login_url2="http://studentlogin.php";
if(type.equals("login1")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url1);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(type.equals("login2")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url2);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
In your method onPostExecute check if the result is correct i.e. login is successful if yes then add code:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("caller", "LoginActivity");
startActivity(i);
finish();
I would also suggest you to dismiss your alertDialog using: alertDialog.dismiss();
I solved this by adding this code into OnPostExecute, and then I declared two activities in the Manifest.xml. thank you for helping me.
protected void onPostExecute(String result) {
if(result.equals("Admin login success")){
Intent intent = new Intent(context, adminpanel.class);
context.startActivity(intent);
}
if(result.equals("Student Login Success")){
Intent intent = new Intent(context, studentpanel.class);
context.startActivity(intent);
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
Ok , so for opening new activity you must use these code with proper format according to your code ,
Intent i = new Intent(FromfirstActivity.this, TosecondActivity.class);
startActivity(i);
It will definatly help, thanks

How to start an activity in BackgroundTask only after verifing that the username and password is correct?

I am trying to start an activity "Display" which is supposed to start only after the user is authenticated (the usernames and passwords are stored in phpmyadmin database)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class PatLogin extends Activity {
EditText a,b;
String login_name,login_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pat_login);
}
public void patbuttonClick(View v) {
if (v.getId() == R.id.patlogin) {
a = (EditText) findViewById(R.id.TFpusername);
b = (EditText) findViewById(R.id.TFppassword);
login_name = a.getText().toString();
login_pass = b.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,login_name,login_pass);
//If possible I would like to call the "Display" activity from here but only when the correct username and password is entered.
//If it's not possible to call from here then I would like to know how to call "Display" activity from "BackgrounTask.java".
}
}
}
The BackgroundTask.java is used to authenticate the user (check if the username and password match) through the phpmyadmin database.
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
int flag=0;
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/mobidoc/login.php";
String method = params[0];
if(method.equals("login"))
{
String login_name = params[1];
String login_pass = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException 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) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
//When I use the following 2 lines of code, It calls the Display activity even if the wrong password is entered. I need a certain condition to be applied.
Intent myIntent = new Intent(ctx, Display.class);
ctx.startActivity(myIntent);
}
}
}
So what I want to do is call an activity named "Display". This activity should be called only when the correct username and password is entered.
I am attaching the php file too, just for reference.
<?php
require "init.php";
$username = $_POST["login_name"];
$password = $_POST["login_pass"];
$password = md5($password);
$sql_query = "select name from pat_info where username like '$username' and password like '$password';";
$result = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
$name = $row["name"];
echo "Login Success... Welcome ".$name;}
else{
echo "Login Failed...Try Again.";
}
Ok I got the solution to it. I had to compare the echo of the php file and compare it with "res" which stores the value of "result". The modified "BackgroundTask.java" is below:
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
String res;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
int flag=0;
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/mobidoc/login.php";
String method = params[0];
if(method.equals("login"))
{
String login_name = params[1];
String login_pass = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
//I stored the response in the following String variable (res)
res = response;
return response;
} catch (MalformedURLException 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) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else if(res.equals("Login Failed...Try Again."))
{
alertDialog.setMessage(result);
alertDialog.show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
Intent myIntent = new Intent(ctx, Display.class);
ctx.startActivity(myIntent);
}
}
}

Not able to print JSON object String in android TextView

So I am trying to fetch JSON string from a website which looks like this
[{"name":"Painting"},{"name":"Painting or varnishing doors"},{"name":"Painting or varnishing frames"},{"name":"Varnishing floors"},{"name":"Picking old wallpaper"},{"name":"Painting the facade"},{"name":"professional athlete"}]
I just want to fetch the first JSONObject with the string "Painting".
Here's my MainActivity.java code
package mobiletest.pixelapp.com.mobiletest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import model.Cup;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private String myString;
private String anotherString;
private String myVar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
Cup myCup = new Cup();
String newString = myCup.myMethod();
try {
JSONArray jsonArray = new JSONArray(newString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.v("Key",jsonObject.getString("name"));
textView.setText(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here's my java class file cup.java
package model;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by pruthvi on 12/2/2015.
*/
public class Cup {
public String myMethod()
{
String output = getUrlContents("http://xyz.co/tests/android-query.php");
return output;
}
private static String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
// many of these calls can throw exceptions, so i've just
// wrapped them all in one try/catch statement.
try
{
// create a url object
URL url = new URL(theUrl);
// create a urlconnection object
URLConnection urlConnection = url.openConnection();
// wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
Now the problem, when I run this code as java I am easily able to print painting from the JSONObject, but when I try to run it as an android view by setting the text for my TextView, I am getting some strange system.err
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest D/libc: [NET] getaddrinfo hn 10, servname NULL, ai_family 0+
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:393)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:244)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:219)
I am new to java and android, and as of now I just want to get data from my remote server files and database.
Thanks in advance
look at this example it will give you an idea
AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
URL url = new URL("http://www.omdbapi.com/?i=&t="
+ TITLE);
String URL2="http://www.omdbapi.com/?i=&t=saw";
Log.d("URL content", url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
Log.d("URL content", "register URL");
urlConnection.connect();
Log.d("URL connection", "establish connection");
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
};
asyncLoad.execute();
Do like that in onCrate Method
try {
JSONArray jsonArray = new JSONArray(newString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name")
textView.setText(name));}
} catch (JSONException e) {
e.printStackTrace();
}
It will set name to textView.
Happy to Help and Happy Coding
You can't do network task in UI Thread.
So
String newString = myCup.myMethod();
not properly working.
Main Reason of those errors are related with thread context.
If you want to do network task with android, use async task or other network library (personally I recommend retrofit).
try
{
JSONArray jsonArray = new JSONArray(newString);
if(jarray.length()>0){
String name = jarray.getJSONObject(0).getString("name");
displayName(name); //new method
}catch(Exception e){
}
Define the method displayName(String) like this outside onCreate()
public void displayName(final String name){
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(jsonObject.getString("name"));
}
});
}

Why this doesn't work for ICS [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange NetworkOnMainThreadException in Android app?
Trying To Upload To Dropbox: NetworkOnMainThreadException?
I have used the below code for reading HTML contents from a url. This works perfectly for 2.3.3 but when I try to run the same code it doesn't work for ICS.
I am trying to append these html contents on to a edittext. But it always remains empty when I run the code on ICS. What may be the problem?
public class Quiz1Activity extends Activity {
private static BufferedReader reader = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText ed = (EditText) findViewById(R.id.editText1);
try {
ed.append(getStringFromUrl("http://www.google.com"));
//getInputStreamFromUrl("").close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("Content stream is " + contentStream);
return contentStream;
}
public static String getStringFromUrl(String url) throws IOException{
reader = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));
StringBuilder sb = new StringBuilder();
try{
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
getInputStreamFromUrl(url).close();
return sb.toString();
}
}
Like #Vipul Shah said you have to move getInputStreamFromUrl() into another thread use Async Task, this is work on ICS:
package com.home.anas;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.EditText;
public class WebPageContentActivity extends Activity {
private EditText ed;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText) findViewById(R.id.editText1);
readWebpage();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
ed.setText(result);
}
}
public void readWebpage() {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.google.com" });
}
}
But it always remains empty when I run the code on ICS. What may be the problem?
Issue is ICS don't allow you do asynchronous task on main thread so move your asynchronous into new thread.
You should move following code in seperate thread.
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("Content stream is " + contentStream);
return contentStream;
}

Categories