I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)
Error shows this line textView.setText(jsonObject.getString("distance"));
My Code
HttpResponse httpResponse;
Button button;
TextView textView;
static JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
new GetDataFromServerIntoTextView(MainActivity.this).execute();
}
});
}
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
String HttpURL = "https://api.myjson.com/bins/1cuzhn";
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textView.setText(jsonObject.getString("distance"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}
I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.
Add below dependencies
// OKHTTP
implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
and
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String>
{
public Context context;
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String strUrl = "https://api.myjson.com/bins/1cuzhn";
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, "Exception while downloading url " + e.toString());
} finally {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
try {
if (data != null) {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here is your all data of distance and time
Log.e(TAG, "distance " + jsonObject.get("distance"));
Log.e(TAG, "time " + jsonObject.get("time"));
}
} else {
Log.e(TAG, "onPostExecute: null json object");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are using POST request where as your api is expecting GET request
Here is more details about GET and POST
HttpPost httpPost = new HttpPost(HttpURL);
replace this with following
HttpGet request = new HttpGet(HttpURL);
To avoid crash replace your code with
textView.setText(jsonObject.getString("distance"));
this
textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));
Related
I need to do an HTTP post with a cookie, and get the JSON response and put it in a TextView in Android Studio.
The code I have so far:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new GetDataSync().execute();
try {
postPHP("Hoi");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
public class GetDataSync extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
getData();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
private void postPHP (String cookie1) throws IOException, JSONException {
CookieManager cookieManager = CookieManager.getInstance();
String cookieString = cookieManager.getCookie(cookie1);
URL url = new URL("http://piggybank.wordmediavormgever.nl/getSaldo.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("thatsallfolks", cookieString);
connection.connect();
OutputStream out = connection.getOutputStream();
out.write(data);
out.flush();
out.close();
}
private void getData() throws IOException, JSONException {
TextView txtUser = (TextView) findViewById(R.id.user);
JSONObject json = readJsonFromUrl("http://piggybank.wordmediavormgever.nl/getSaldo.php");
try {
String response = json.getString("saldo");
Log.e("saldo", response);
response = json.getString("saldo");
txtUser.setText(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
As you can see, the JSON to TextView and HTTP POST request are two seperate pieces of code, that's why I don't get the correct JSON value. I need to combine the two so it first sends the cookie via POST and then puts the JSON response in a TextView, but I don't know how
Change your code as follows:
public class GetDataSync extends AsyncTask<Void, Void, String> {
private final String cookie;
public GetDataSync(String cookie) {
this.cookie = cookie;
}
#Override
protected String doInBackground(Void... voids) {
try {
postPHP();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return getData();
}
#Override
protected void onPostExecute(String resposne) {
super.onPostExecute(s);
TextView txtUser = (TextView) findViewById(R.id.user);
txtUser.setText(resposne);
}
private void postPHP () throws IOException, JSONException {
CookieManager cookieManager = CookieManager.getInstance();
String cookieString = cookieManager.getCookie(cookie);
URL url = new URL("http://piggybank.wordmediavormgever.nl/getSaldo.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("thatsallfolks", cookieString);
connection.connect();
OutputStream out = connection.getOutputStream();
out.write(data);
out.flush();
out.close();
}
private String getData() {
JSONObject json = readJsonFromUrl("http://piggybank.wordmediavormgever.nl/getSaldo.php");
try {
String response = json.getString("saldo");
Log.e("saldo", response);
response = json.getString("saldo");
return response;
} catch (Exception e) {
return "";
}
}
}
Execute the task in onCreate as follows:
new GetDataSync("Hoi").execute();
I found the code below from a website and it seems it might help me in my android application. But the problem is, the code below is for an activity only and I need to run the code in a fragment. BTW my application is about downloading the images from the online database and storing it to a listview.
What should I do?
This is the code I want to use:
public class GetJsonFromUrlTask extends AsyncTask<Void, Void, String> {
private Activity activity;
private String url;
private ProgressDialog dialog;
private final static String TAG = GetJsonFromUrlTask.class.getSimpleName();
public GetJsonFromUrlTask(Activity activity, String url) {
super();
this.activity = activity;
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progress dialog
dialog = new ProgressDialog(activity);
// Set progress dialog title
dialog.setTitle("Getting JSON DATA");
// Set progress dialog message
dialog.setMessage("Loading...");
dialog.setIndeterminate(false);
// Show progress dialog
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
// call load JSON from url method
return loadJSON(this.url).toString();
}
#Override
protected void onPostExecute(String result) {
((CategoryListViewActivity) activity).parseJsonResponse(result);
dialog.dismiss();
Log.i(TAG, result);
}
public JSONArray loadJSON(String url) {
// Creating JSON Parser instance
JSONGetter jParser = new JSONGetter();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
return json;
}
private class JSONGetter {
private InputStream is = null;
private JSONArray jObj = null;
private String json = "";
// constructor
public JSONGetter() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),
8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
There is easy step to use AsyncTask within fragment just as follow
place code on activityCreateview
new GetJsonFromUrlTask(getActivity(), mListView).execute("");
getActivity() is method to getting your activity context in to Fragment class
Note: As you found code from website this code is a AsyncTask class you can call this code in to Activity,Fragment, any other Class also
Change code
public class GetJsonFromUrlTask extends AsyncTask<Void, Void, String> {
private Context activity;
private String url;
private ProgressDialog dialog;
private final static String TAG = GetJsonFromUrlTask.class.getSimpleName();
public GetJsonFromUrlTask(Context activity, String url) {
super();
this.activity = activity;
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progress dialog
dialog = new ProgressDialog(activity);
// Set progress dialog title
dialog.setTitle("Getting JSON DATA");
// Set progress dialog message
dialog.setMessage("Loading...");
dialog.setIndeterminate(false);
// Show progress dialog
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
// call load JSON from url method
return loadJSON(this.url).toString();
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
Log.i(TAG, result);
}
public JSONArray loadJSON(String url) {
// Creating JSON Parser instance
JSONGetter jParser = new JSONGetter();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
return json;
}
private class JSONGetter {
private InputStream is = null;
private JSONArray jObj = null;
private String json = "";
// constructor
public JSONGetter() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),
8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
I'm currently studying this tutorial http://www.android-examples.com/android-json-parsing-retrieve-from-url-and-set-mysql-db-data/
It runs perfectly but now I would like to display all of the JSON values in the text view. I am new to JSON and only has a bit of experience in android.
Here is my MainActivity.java. I modified it a bit from the tutorial
public class MainActivity extends Activity {
TextView textview;
JSONObject json = null;
String str = "";
HttpResponse response;
Context context;
ProgressBar progressbar;
Button button;
JSONArray jArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar)findViewById(R.id.progressBar1);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressbar.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
new GetTextViewData(context).execute();
}
});
}
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
private class GetTextViewData extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetTextViewData(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.9:80/test-androidex/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textview.setText(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressbar.setVisibility(View.GONE);
}
}
and this is my JSON. It is a lot different from the tutorial
[{"id":"1","name":"white","status":"0"},{"id":"2","name":"red","status":"10"},{"id":"5","name":"blue","status":"15"}]
So obviously my code only displays the first name "white". I can't understand how to iterate the JSONObject to display all the values. I tried the answers in other questions but I can't quite incorporate them in my code.
That's because you're just getting the first element from JSONArray. (Index 0)
You should iterate over JSONArray to get all the JSONObject within an array.
Like this,
JSONArray jArray = new JSONArray(str);
int total=jArray.length();
for(int i=0;i<total;i++) {
JSONObject json = jArray.getJSONObject(i); // Replace 0 with i'th index.
// use this json object to iterate over individual objects.
}
Here's example of json parsing and insert , update , delete or get data from server with source you should try this !
Happy Coding!
The problem of your code is what Alok Patel stated. But I see that the logic of your code needs some changes to do what you want (according to sample json that you posted). You called parse method on values which are in fact simple data while you should call it on jsonObjects.
I refactored your code as below to do what you want:
public class MainActivity extends Activity {
TextView textview;
JSONObject json = null;
String str = "";
HttpResponse response;
Context context;
ProgressBar progressbar;
Button button;
JSONArray jArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar)findViewById(R.id.progressBar1);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressbar.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
new GetTextViewData(context).execute();
}
});
}
private class GetTextViewData extends AsyncTask<Void, Void, Void>
{
public Context context;
Map<String,String> out = new Map<String, String>();
public GetTextViewData(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.9:80/test-androidex/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
int total=jArray.length();
for(int i=0;i<total;i++) {
JSONObject json = jArray.getJSONObject(i);
parse(json, out);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
// print "out" object to console here by iterating over its keys
// or do any needed process on it here.
textview.setText(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressbar.setVisibility(View.GONE);
}
Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
val = json.getString(key);
}catch(Exception e){
}
if(val != null){
out.put(key,val);
}
}
return out;
}
}
Sooo here is my OnCreateView code
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
tvMemberName = (TextView) v.findViewById(R.id.member_name);
UrlPostHelper uph = new UrlPostHelper();
uph.execute();
return v;
}
and AsyncTask
private class UrlPostHelper extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String url = "http://localhost:8080/MP/Profile";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
String data = "no response";
try {
response = httpClient.execute(httpGet);
data = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s = "yow";
try {
JSONArray ja = new JSONArray(data);
for (int i = 0 ; i < ja.length(); i++ ){
JSONObject j = ja.getJSONObject(i);
String firstName = j.getString("firstName");
String lastName = j.getString("lastName");
System.out.println(firstName);
s = firstName +" " + lastName;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.i("TAG", result );
tvMemberName.setText(result);
}
}
My problem is that in my android app it does not show anything at first but after a while like around 1-2 minutes the "yow" will show. It is not replaced with the member name though. I tried running my servlet and it works just fine. Please help me.
AsyncTask<Params, Progress, Result>.
private class UrlPostHelper extends AsyncTask<Void, Void, String>{
private EditText tvMemberName;
public UrlPostHelper(EditText tv){
this.tvMemberName = tv;
}
Return Text after background task finished.
#Override
protected String doInBackground(Void... params) {
HttpResponse response;
String data = "no response";
try {
response = httpClient.execute(httpGet);
data = getJSONString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
return data; //Text to set TvMember Value
}
Get String from response Util.
public String getJSONString(InputStream is) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
Set EditText onPostExecute.
protected void onPostExecute(String result){
Log.i("TAG", result );
tvMemberName.setText(result);
}
Pass EditText with the UrlPostHelper call.
new UrlPostHelper(tvMemberName).excute();
public class DetailsActivity extends Activity {
private ArrayAdapter<Imageclass> adapter;
ArrayList<String> imageselect = new ArrayList<String>();
private ArrayList<Imageclass> array1;
private ArrayList<Imageclass> list = new ArrayList<Imageclass>();
//private ArrayList<Imageclass> array;
ArrayList<String> imagetest = new ArrayList<String>();
private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
int id;
int pid;
int val;
int val_new;
double lati;
double longi;
String imagename;
//private ImageView image;
//public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
ImageView image;
static Bitmap bm;
ProgressDialog pd;
BitmapFactory.Options bmOptions;
public class test extends AsyncTask<Void, Void, InputStream>{
ArrayList<Imageclass> str;
private DetailsActivity activity;
public test(DetailsActivity activity){
this.activity = activity;
}
#Override
protected InputStream doInBackground(Void... params) {
//String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id);
Log.e("Checking id",""+id);
String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id);
URL url;
try {
stringURL=stringURL.replaceAll(" ", "%20");
url = new URL(stringURL);
Log.e("URL",""+ url);
URLConnection conn= url.openConnection();
Log.e("URLConnection",""+conn );
InputStream stream= conn.getInputStream();
Log.e("URLStream",""+stream );
return stream;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("Excepiton", ""+e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
Log.e("Result", ""+result);
StringBuilder builder = new StringBuilder();
Log.e("Builder", ""+ builder);
BufferedReader reader = new BufferedReader(new InputStreamReader(result));
Log.e("Reader", ""+ reader);
String line = null;
try {
while((line = reader.readLine()) != null) {
Log.e("Result11", ""+ builder.append(line));
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String jsonString = builder.toString();
Log.e("image", jsonString);
try {
JSONObject rootObject = new JSONObject(jsonString);
Log.e("JSOnObject",""+ rootObject);
JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images");
//array1.clear();
ArrayList<String> imagearray = new ArrayList<String>();
for (int index = 0; index < jsonArray.length(); index++) {
Imageclass imageinstance = new Imageclass();
JSONObject object = (JSONObject) jsonArray.get(index);
Log.e("Image test", "" + object);
imageinstance.image = object.getString("file_name");
//### this contain the image name
Log.e("Imageinstance.image",""+imageinstance.image);
imagename = imageinstance.image;
imagearray.add(imageinstance.image);
array1.add(imageinstance);
//array1.add(imagearray);
Log.e("array1","test"+array1);
}
Log.e("IMAGES",""+array1);
activity.setlist(array1);
}
catch (JSONException e) {
Log.e("this Exception",""+ e);
e.printStackTrace();
}
catch (Exception e) {
Log.e("NULL","NULL"+e);
}
// adapter.notifyDataSetChanged();
}
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... param) {
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
Log.e("inside img",""+Finalname);
Log.e("inside img_val",""+val);
Log.e("Check","check"+imageUrl);
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
Log.e("Test","Test"+ imageUrl.equals(""));
image.setImageBitmap(bm);
} else {
Toast.makeText(DetailsActivity.this,
"test", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
String Finalname;
//String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname;
public void setlist(ArrayList<Imageclass> list)
{
this.list= list;
Log.e("LIST",""+ this.list);
String imagename1 = list.toString();
Log.e("image new value",""+imagename1);
this.list= list;
Log.e("testing",""+ this.list);
for (int i=0; i < list.size(); i++)
{
Log.e("new check",""+list.get(i));
//String test2= list.get(i).toString();
imagetest.add(list.get(i).toString());
Finalname = list.get(i).toString();
getimage_name(Finalname);
Log.e("Come",""+list.get(i).toString());
Log.e("Finalname",""+Finalname);
}
}
//String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
private void getimage_name(String finalname2) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
image = (ImageView)findViewById(R.id.imageView2);
// getMenuInflater().inflate(R.menu.details);
//R.id.textDetailPlace
textView1 = (TextView)findViewById(R.id.textDetailPlace);
textView2 = (TextView)findViewById(R.id.textDetailAddress );
textView3 = (TextView)findViewById(R.id.textCapacity);
// textView4 = (TextView)findViewById(R.id.textDetailContactNo);
textView5 = (TextView) findViewById(R.id.textViewDescription);
textView1.setText(getIntent().getExtras().getString("test"));
textView2.setText(getIntent().getExtras().getString("test2"));
textView3.setText(getIntent().getExtras().getString("test3"));
//textView4.setText(getIntent().getExtras().getString("test4"));
textView5.setText(getIntent().getExtras().getString("test5"));
id = getIntent().getExtras().getInt("test6");
Log.e("ID value",""+id);
pid = getIntent().getExtras().getInt("test7");
Log.e("PID value",""+pid);
lati = getIntent().getExtras().getDouble("testlat");
Log.e("long",""+lati);
longi = getIntent().getExtras().getDouble("testlong");
Log.e("long",""+longi);
val=pid;
Log.e("val",""+val);
ActionBar actionBar = getActionBar();
actionBar.hide();
pd = ProgressDialog.show(DetailsActivity.this, null, null,true);
pd.setContentView(R.layout.progress);
array1 = new ArrayList<Imageclass>();
//new test(this).execute();
new test(this).execute();
here test asynctask is called
Log.e("JUST","CHECK");
Log.e("JUST","CHECK");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here imageDownload asynctask is getting called::
new ImageDownload().execute();
Log.e("imagename",""+imagename);
}
}
here before ImageDownload is start executing before test async task is complete
and i am not able to get the status of the task can u tell how it is done
whatever i understood from this you want to execute your ImageDownload thread after the task thread,so start the ImageDownload Thread from the onPostExecute() of your task thread
When executing an async task a new thread is started, but your current thread keeps running. It immediately runs into your thread.sleep(1000) just after starting test.async.
It looks like your doing some internet downloading in test.async, and as you might have guessed, it takes longer than 1000 milliseconds (1 second). This means 1 second later, your other async is starting, before the first completed.
I assume you want to stagger them. In the postExecute of the first async, you can spawn the second async. A more stylistically correct method would be to implement an interface on your activity that takes a callback on Async completion, then upon receiving the call back, launch your second async.
An example of how to structure this is below.
interface AsyncCallback{
void onAsyncComplete();
}
public class ExampleActivity extends Activity implements AsyncCallback {
....
public void launchFirstAsync(){
new Task(this).execute();
}
#Override
public void onAsyncComplete() {
//todo launch second asyncTask;
}
}
class Task extends AsyncTask<Void, Void, Void>{
AsyncCallback cb;
Task(AsyncCallback cb){
this.cb = cb;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
cb.onAsyncComplete();
}
}
Have a look here, This Help me for same..Pass your url to GetTemplateImageController and get the result in Bitmap array
GetTemplateImageController Class:
public class GetTemplateImageController extends AsyncTask<String, Void, Bitmap[]>
{
Context mcontext;
private ProgressDialog pDialog;
public static String[] imageurls;
public static Bitmap bm[]=new Bitmap[15];
// URL to get JSON
private static final String url= "http://xxx.xxx.xxx.xxx/image_master.php?";
private static final String TEMPLATE = "Template_images";
private static final String IMAGEURLS = "tempimagename";
// JSONArray
JSONArray loginjsonarray=null;
//result from url
public GetTemplateImageController(Context c) {
this.mcontext=c;
}
protected void onPreExecute() {
// Showing progress dialog
super.onPreExecute();
pDialog=new ProgressDialog(mcontext);
pDialog.setMessage("Loading");
pDialog.setCancelable(true);
pDialog.setIndeterminate(true);
pDialog.show();
}
protected Bitmap[] doInBackground(String... arg) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("templateMasterId",arg[0].toString()));
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, params);
Log.d("Response: ", ">"+jsonstr);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(TEMPLATE);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(IMAGEURLS);
}
for(int i=0;i<imageurls.length;i++){
bm[i]=DownloadImage(imageurls[i]);
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Toast.makeText(mcontext,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return bm;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch(Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Integer result) {
// Dismiss the progress dialog
pDialog.dismiss();
if(result != null)
Toast.makeText(mcontext,"Download complete", Toast.LENGTH_SHORT).show();
//}
}
}
ServiceHandler Class:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpEntity httpEntity=null;
HttpResponse httpResponse=null;
// Checking http request method type
if(method==POST){
HttpPost httpPost=new HttpPost(url);
if(params!=null)
{
//adding post params
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse=httpClient.execute(httpPost);
}
else if(method==GET)
{
// appending params to url
if(params!=null)
{
String paramString=URLEncodedUtils.format(params, "utf-8");
url +="?"+paramString;
}
HttpGet httpGet=new HttpGet(url);
httpResponse=httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
}
Over time there have been several changes to the way Android deals with AsyncTasks that run concurrently. In very old Android versions (pre-1.6 afaik) multiple AsyncTasks were executed in sequence. That behavior has been changed to run the AsyncTasks in parallel up until Android 2.3. Beginning with Android 3.0 the the Android team decided that people were not careful enough with synchronizing the tasks that run in parallel and switched the default behavior back to sequential execution. Internally the AsyncTask uses an ExecutionService that can be configured to run in sequence (default) or in parallel as required:
ImageLoader imageLoader = new ImageLoader( imageView );
imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" );