Hi I have a JSON Data and I'm getting it through url by using get method,I need to show the sender,receiver,message in Textview,I have created a JsonParser class also but after running the app its showing Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference.How to fix this issue.
Here is what I have tried
private static String url = "http://130.211.99.188/api/messages";
JSONArray _items = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView)findViewById(R.id.textView1);
t2 = (TextView)findViewById(R.id.textView2);
t2 = (TextView)findViewById(R.id.textView3);
if (Utils.isNetConnected(this))
{
new Parser().execute();
}
else
Utils.showDialog(this);
}
class Parser extends AsyncTask < String, String, String > {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONData(url);
try{
_items = json.getJSONArray("_updated");
for(int i=0;i<_items.length();i++){
JSONObject object = _items.getJSONObject(i);
sender = object.getString("sender");
receiver = object.getString("receiver");
message = object.getString("message");
}
}catch(JSONException e){
e.printStackTrace();
}
return message;
}//Ending doInBackground
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
t1.setText(sender);
t2.setText(receiver);
t3.setText(message);
}
}
}
This is my JSON Data
{"_items": [{"_updated": "Thu, 01 Jan 1970 00:00:00 GMT", "sender": "556a1233aca33b3c8158de0a", "timestamp": 1433018976, "receiver": "5569c6c5aca33b3c8158de07", "_links": {"self": {"href": "messages/556a2260aca33b3c8158de11", "title": "messages"}}, "message_created": "Sat, 30 May 2015 20:49:36 GMT", "seen": false, "message": "hii", "_id": "556a2260aca33b3c8158de11", "_etag": "afa4fe57efec9abf7c5bc817a7e045a5b4467384", "_created": "Thu, 01 Jan 1970 00:00:00 GMT"},
This is the complete code, have a look at the data printed
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class MainActivity extends Activity {
ProgressDialog pdialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new postServer().execute();
}
public String postData() throws JSONException {
// Create a new HttpClient and Post Header
String downloadedString = null;
HttpClient httpclient = new DefaultHttpClient();
// for registerhttps://te
// HttpPost httppost = new HttpPost("http://130.211.99.188/api/messages");
HttpClient myClient = new DefaultHttpClient();
// HttpPost myConnection = new HttpGet("http://130.211.99.188/api/messages");
try {
// HttpResponse response = myClient.execute(myConnection);
HttpResponse httpResponse = httpclient.execute(new HttpGet("http://130.211.99.188/api/messages"));
downloadedString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("downloadedString:in login:::"
+ downloadedString);
return downloadedString;
}
public class postServer extends AsyncTask<Void, Void, Void> {
String jsonstring = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(MainActivity.this);
pdialog.setCancelable(false);
pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pdialog.setMessage("Loading..");
pdialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
jsonstring = postData();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
if(pdialog!=null){
pdialog.dismiss();
}
JSONObject mainObject = new JSONObject(jsonstring);
JSONArray array=mainObject.getJSONArray("_items");
for(int i=0;i<array.length();i++){
System.out.println(array.getJSONObject(i).getString("sender"));
System.out.println(array.getJSONObject(i).getString("receiver"));
System.out.println(array.getJSONObject(i).getString("message"));
}
} catch (Exception e) {
// TODO: handle exception
if (pdialog != null) {
pdialog.dismiss();
}
System.out.println(e.getMessage());
}
}
}
}
Thanks
Have you tried just declaring the JSONArray variable without assigning it a null value? JSONArray _items;
_items = json.getJSONArray("_updated");
Change to
_items = json.getJSONArray("_items");
And
class Parser extends AsyncTask < String, String, String > {
to
class Parser extends AsyncTask < void, void, void > {
Try this code:
class Parser extends AsyncTask < String, String, String > {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONData(url);
try{
_items = json.getJSONArray("_items");
for(int i=0; i<_items.length(); i++){
JSONObject object = _items.getJSONObject(i);
sender = object.optString("sender");
receiver = object.optString("receiver");
message = object.optString("message");
}
}
catch(JSONException e){
e.printStackTrace();
}
return message;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
t1.setText(sender);
t2.setText(receiver);
t3.setText(message);
}
}
Try to use optString() instead of getString() because the former returns null if doesn't exist and it doesn't throw an exception
Are you sure getJSONData(url) in JSONObject json = jParser.getJSONData(url); is not returning null?
Your question indicates that you are calling getJSONArray() on a null object. Which means the JSON object you queried from the parser is null
Related
I am new for Android i want to know how to connect database.I saw one video in you tube and i follow hole video but its not working.i don't know where i made mistake. please help me.from one week an words i'm trying but now also i'm not getting solution please help me stack over flow.
class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT=1000*15;
public static final String
SERVER_ADDRESS="http://192.168.1.11/myfolder/new1.php";
public ServerRequests(Context context){
progressDialog=new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("processing");
progressDialog.setMessage("please wait.....");
}
public void storeUserDataInBackground(User user,GetUserCallbackuserCallback{
progressDialog.show();
new StoreUserDataAsyncTask(user,userCallback).execute();
}
public void fetchUserDataInBackground(User user,GetUserCallback callBack){
progressDialog.show();
new fetchUserDataAsynctask(user,callBack).execute();
}
public class StoreUserDataAsyncTask extends AsyncTask<Void,Void,Void>{
User user;
GetUserCallback userCallback;
public StoreUserDataAsyncTask(User user,GetUserCallback userCallback){
this.user=user;
this.userCallback=userCallback;
}
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair>dataToSend=new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name",user.name));
dataToSend.add(new BasicNameValuePair("age",user.age + ""));
dataToSend.add(new BasicNameValuePair("username",user.username));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
client.execute(post);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onpostExecute(Void aVoid){
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(aVoid);
}
}
public fetchUserDataAsyncTask extends AsyncTask<Void,Void,User>{
User user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(User user,GetUserCallback userCallback){
this.user=user;
this.userCallback = userCallback;
}
#Override
protected User doInBackground(Void... params){
ArrayList<NameValuePair>dataToSend=new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username",user.username));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser=null;
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
HttpResponce httpResponce=client.execute(post);
HttpEntity entity=httpResponce.getEntity();
String result= EntityUtils.toString(entity);
JSONObject jObject=new JSONObject(result);
if (jObject.length()==0){
user=null;
}else{
String name=jObject.getString("name");
int age =jObject.getInt("age");
returnedUser=new User(name,age,user.username,user.password);
}
}catch (Exception e){
e.printStackTrace();
}
return returnedUser;
}
#Override
protected void onPostExecute(User returnedUser){
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(returnedUser);
}
}
}
enter code here
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button blogin;
EditText etusername,etpassword;
TextView tvregister;
UserLocalStore userLocalStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
etusername=(EditText)findViewById(R.id.username_edit);
etpassword=(EditText)findViewById(R.id.password_edit);
blogin=(Button)findViewById(R.id.login_button);
tvregister=(TextView)findViewById(R.id.tv_register);
blogin.setOnClickListener(this);
tvregister.setOnClickListener(this);
userLocalStore=new UserLocalStore(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_button:
String username=etusername.getText().toString();
String password=etpassword.getText().toString();
User user=new User(username,password);
authenticate(user);
userLocalStore.storeUserData(user);
userLocalStore.setUserLoggedIn(true);
break;
case R.id.tv_register:
startActivity(new Intent(this,RegisterActivity.class));
break;
}
}
private void authenticate(User user) {
ServerRequests serverRequests = new ServerRequests(this);
serverRequests.fetchUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
if (returnedUser == null) {
showErrorMessage();
}else {
logUserIn(returnedUser);
}
}
});
}
private void showErrorMessage() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LoginActivity.this);
dialogBuilder.setMessage("Incorrect user details");
dialogBuilder.setPositiveButton("ok", null);
dialogBuilder.show();
}
private void logUserIn(User returnedUser){
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
startActivity(new Intent(this,MainActivity.class));
}
}
Here is the link which you can refer for fetching data from server.
For Creating Web Service using PHP Click here
<?php
include("connect.php");
$result="";
//get data from users (name for user variable is p1 and p2
//here I am stroing this value to par1 and par2
//method i am using is GET
$par1=$_GET['p1'];
$par2=$_GET['p2'];
$eve = "select * from table where field1='$par1' and field2='$par2'";
$re = mysql_query($eve);
$response = array();
$posts = array();
while($rt = mysql_fetch_array($re))
{
$f1=$rt['field1'];
$f2=$rt['field2'];
break;
}
$posts[] = array('p1'=> $f1,'p2'=> $f2);
$response['posts'] = $posts;
echo stripslashes(json_encode( array('item' => $posts)));
?>
For AsyncTask Example Click here
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Login extends AppCompatActivity {
boolean remember;
private ProgressDialog pDialog;
public static final String PREFS_NAME = "Preference";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
((Button) findViewById(R.id.btnlogin)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Login Validation
try {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Verifying...");
pDialog.show();
LoginVerifyTask g = new LoginVerifyTask();
g.execute(((EditText) findViewById(R.id.mobile)).getText().toString(), ((EditText) findViewById(R.id.password)).getText().toString());
} catch (Exception e) {
Log.e("cs", "catch error");
}
}
});
((TextView) findViewById(R.id.newuserregistrationtxtview)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Registration1.class);
startActivity(i);
}
});
}
public class LoginVerifyTask extends AsyncTask<String, Void, String>
{
String u,p;
void LoginActivity(String s)
{
}
#Override
protected void onPostExecute(String json) {
// TODO Auto-generated method stub
pDialog.dismiss();
pDialog = null;
if (json == null)
{
return;
}
String csv="";
try {
JSONObject js = new JSONObject(json);
JSONArray user = js.getJSONArray("item");
for(int i=0;i<user.length();i++)
{
JSONObject j2 = user.getJSONObject(i);
//received data
String result = j2.get("p1").toString();
break;
}
}
catch(JSONException js)
{
}
return;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
u = params[0];
p = params[1];
String tempdata="";
String buffer="";
try
{
URL url = new URL("http://websitename.com/folder/webservice.php?p1=" + params[0].replace(" ", "%20") + "&p2=" + params[1].replace(" ", "%20"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
//buffer = new String();
if(is==null)
{
return tempdata;
}
else
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line="";
while( (line = reader.readLine())!=null)
{
buffer += line;
}
return buffer;
}
}
catch(Exception e)
{
Log.e("cs", e.toString());
}
return buffer;
}
}
}
package com.example.editartist;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText txtArtistType;
EditText txtPhoneNo;
EditText txtDescription;
Button btnSave;
Button btnDelete;
String uid="1";
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String url_profile_details = "http://10.0.2.2/android_main/get_profile_details.php";
private static final String url_update_profile = "http://10.0.2.2/android_main/update_profile.php";
private static final String url_delete_profile = "http://10.0.2.2/android_main/delete_profile.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PROFILE = "profile";
private static final String TAG_UID = "uid";
private static final String TAG_ARTIST_TYPE = "artist_type";
private static final String TAG_PHONE_NO = "phone_no";
private static final String TAG_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
new GetProfileDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update profile
new SaveProfileDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting profile in background thread
new DeleteProfile().execute();
}
});
}
class GetProfileDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading profile details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", uid));
JSONObject json = jsonParser.makeHttpRequest(
url_profile_details, "GET", params);
// check your log for json response
Log.d("Single Profile Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received profile details
JSONArray profileObj = json
.getJSONArray(TAG_PROFILE); // JSON Array
// get first profile object from JSON Array
JSONObject profile = profileObj.getJSONObject(0);
// profile with this uid found
// Edit Text
txtArtistType = (EditText) findViewById(R.id.inputArtistType);
txtPhoneNo = (EditText) findViewById(R.id.inputPhoneNo);
txtDescription = (EditText) findViewById(R.id.inputDescription);
// display profile data in EditText
txtArtistType.setText(profile.getString(TAG_ARTIST_TYPE));
txtPhoneNo.setText(profile.getString(TAG_PHONE_NO));
txtDescription.setText(profile.getString(TAG_DESCRIPTION));
}else{
// profile with uid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save profile Details
* */
class SaveProfileDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Saving profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving profile
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String artistType = txtArtistType.getText().toString();
String phoneNo = txtPhoneNo.getText().toString();
String description = txtDescription.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_UID, uid));
params.add(new BasicNameValuePair(TAG_ARTIST_TYPE, artistType));
params.add(new BasicNameValuePair(TAG_PHONE_NO, phoneNo));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
// sending modified data through http request
// Notice that update profile url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_profile,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("UPDATE","Successfully updated");
} else {
// failed to update profile
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once profile updated
pDialog.dismiss();
}
}
class DeleteProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Deleting Profile...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", uid));
JSONObject json = jsonParser.makeHttpRequest(
url_delete_profile, "POST", params);
Log.d("Delete Profile", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("DELETE","Successfully deleted");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
package com.example.editartist;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
The app will show Loading Profiles dialog for two seconds and then it simply closes like: EditArtist has stopped working. There is long list of errors in the log starting with
10-05 10:53:33.000: E/AndroidRuntime(1057): FATAL EXCEPTION: main
10-05 10:53:33.000:E/AndroidRuntime(1057): android.os.NetworkOnMainThreadException
I have taken uid="1" for the sake of ease here and so only the user with uid=1 can be edited.
Remove
runOnUiThread(new Runnable() {
public void run() {}
});
from the asynctask`s doInBackground().
Asynctask is itself is a thread in which you are doing network operations.If you write runonUiThread() on doinBackground then the network operation will perform in the main thread only and it will encounter the exception that you are facing.Hence there will be no point of writting an asynctask.
You cannot run network request in Main UI thread...to process JSON properly you have run it on different thread using new Thread or use AsynTask
I am trying to use a thread to do some work in the background which takes a few seconds.
I was trying to display a progress dialog but its not displaying at all.
I thought it would be better to use an Async task but whenever I try I cannot get it to work, mostly because I cannot access the variables I need to modify within the Async task.
Here is my thread which is called when a button is clicked:
Thread thread = new Thread()
{
#Override
public void run() {
try {
for (String s : dLinks) {
String pathToFile = s.substring(1));
dURLs.add(dFs.fetchLink(pathToFile, false).toString());
}
} catch (DbxException e) {
dURL = null;
e.printStackTrace();
}
}
};
thread.start();
try {
thread.join(); // I added this as the next part of my code was executing before the thread was finished
} catch (InterruptedException e) {
e.printStackTrace();
}
Could I move this to an Async task, update a progress bar or at least show a spinner AND pass back the array dURLs to the Main thread?
Here we called AsyncTask with activity's context this which will feed to AsyncTask to show ProgressDialog in these Activity while AsyncTask runs in background.
public void onCreate(Bundle savedInstanceState)
{
SpinnerDataTask spinnerDataTask = new SpinnerDataTask(this);
spinnerDataTask.execute(null);
}
AsyncTask has method which uses to do background work in doInBackground() and post the result in onPostExecute(). To show view whenever AsyncTask start working, onPreExecute() is perfect to show that something is working in background.
private class SpinnerDataTask extends AsyncTask<Void Void, Void>
{
Context context;
public SpinnerDataTask(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
for (String s : dLinks) {
String pathToFile = s.substring(1));
dURLs.add(dFs.fetchLink(pathToFile, false).toString());
}
} catch (DbxException e) {
dURL = null;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog.isShowing())
{
pDialog.dismiss();
}
}
}
you can use like this:
public class web_api_get_thread extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(context);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.show();
progressDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... params) {
StringBuilder builder = new StringBuilder();
//do your work
return builder.toString();
} // protected Void doInBackground(String... params)
protected void onPostExecute(String string) {
this.progressDialog.dismiss();
// see your result here
}
}
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 de.vogella.android.asyntask.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class ReadWebpageAsyncTask extends Activity {
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.TextView01);
}
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) {
textView.setText(result);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.vogella.com" });
}
}
Create the following layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/readWebpage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Load Webpage" >
</Button>
<TextView
android:id="#+id/TextView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Placeholder" >
</TextView>
</LinearLayout>
refer to :http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
Hi I have one problem with ProgressDailog. I'm not able to set it properly in my code. In my code I'm getting URLs of images through JSON Array and downloading that images after that showing them into GridView and on click displaying selected image on next activity..This all work perfectly but the problem is As I'm using AsyncTask in my code it goes in background and fetch JSON, download images. I want to show ProgressBar till background process is completed and initialize the GridView after all images get downloaded ...
Following is my code..
public class AndroidGridLayoutActivity extends Activity {
public static ImageAdapter img;
public static String[] imageurls;
public static GridView gridView;
public static Bitmap bm[]=new Bitmap[4];
private ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
// Showing progress dialog
pDialog = new ProgressDialog(this);
pDialog.setMax(5);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
new GetImageUrls().execute();
Thread thread = new Thread()
{
#Override
public void run() {
int count=0;
while(count<3) {
try {
sleep(1000);
count++;
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
if(pDialog != null && pDialog.isShowing()){
pDialog.dismiss();
}
new GetImageUrls().execute();
}
};
thread.start();
gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
img = new ImageAdapter(AndroidGridLayoutActivity.this,bm);
gridView.setAdapter(img);
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
}
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context = getBaseContext();
private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
private static final String MAIN = "mainCategory";
private static final String SUB = "mcatimage";
JSONArray loginjsonarray=null;
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(MAIN);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(SUB);
}
for(int i=0;i<imageurls.length;i++)
{
bm[i]=DownloadImage(imageurls[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
Log.d("DownloadImage: ", url.toString());
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();
Log.d("DownloadImage response: ", Integer.toString(response));
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("DownloadImage: ", in.toString());
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
Log.d("DownloadImage Bitmap: ", bitmap.toString());
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
}
}
As I run this code the images get downloaded but not display on grid view and as I click on any Grid the image displays on next activity,,
ImageAdapter Class:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public static Bitmap adapterbm[]=new Bitmap[4];
ImageView imageView;
public static String[] imageurls;
// Constructor
public ImageAdapter(Context c, Bitmap[] bm){
mContext = c;
adapterbm = bm;
}
public ImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return adapterbm.length;
}
#Override
public Object getItem(int position) {
return adapterbm[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
imageView = new ImageView(mContext);
imageView.setImageBitmap(adapterbm[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
You should Override onPreExecute() method before doInBackground method.
ProgressDialog myPd_bar;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar=new ProgressDialog(AndroidGridLayoutActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(title);
myPd_bar.show();
super.onPreExecute();
}
Then you should Override onPostExecute() method after doInBackground method.
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
myPd_bar.dismiss();
}
You can find more information from this link
Place your ProgressDialog in onPreExecute, hope this code helps you out :)
private ProgressDialog pdia;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(yourContext);
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pdia.dismiss();
}
There are two more method in Async class i.e onPostExecute and onPreExecute method. in onPreExecute method you can write the following code
pDialog = new ProgressDialog(this);
pDialog.setMax(5);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
And onPostExecute method use pDialog.dismiss().
Use preExcecute to display progress dialog.
ProgressDialog pDialog;
public class GetImageUrls extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg)
{....
}
#Override
protected postExcecute()
{
pDialog.dismiss();
....//display UI
...
}
There is no need of writing Thread to show ProgressDialog.
Just simply you need to implement onPreExecute to show the dialog and onPostExecute to dismiss the dialog.
Just change your GetImageUrls method as below:
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context = getBaseContext();
private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
private static final String MAIN = "mainCategory";
private static final String SUB = "mcatimage";
JSONArray loginjsonarray=null;
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(this);
pDialog.setMax(5);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(MAIN);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(SUB);
}
for(int i=0;i<imageurls.length;i++)
{
bm[i]=DownloadImage(imageurls[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pDialog.dismiss();
}
Start dialog in
onPreExecute()
and dismiss it
onPostExecute()
The easiest way to show progress while doing background process!
private class GetImageUrls extends AsyncTask<String, String , String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(this,null, "Loading ...", true);
progressDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... arg0) {
//background process
}
protected void onProgressUpdate(String... str) {
}
protected void onPostExecute(String result) {
progressDialog.dismiss(); // once process complete it will dismiss.
}
}
Use beelow code:
ProgressDialog mProgressDialog;
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context = getBaseContext();
private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
private static final String MAIN = "mainCategory";
private static final String SUB = "mcatimage";
JSONArray loginjsonarray=null;
#Override
protected void onPreExecute(){
super.onPreExecute();
mProgressDialog = ProgressDialog.show(AndroidGridLayoutActivity.this,
"", "Loading...");
mProgressDialog.setCancelable(false);
}
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(MAIN);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(SUB);
}
for(int i=0;i<imageurls.length;i++)
{
bm[i]=DownloadImage(imageurls[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
Log.d("DownloadImage: ", url.toString());
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();
Log.d("DownloadImage response: ", Integer.toString(response));
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("DownloadImage: ", in.toString());
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
Log.d("DownloadImage Bitmap: ", bitmap.toString());
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
}
#Override
protected void onPostExecute(){
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
}
Try this
Activity class
package com.example.imagelist;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ItemsAdapter adapter;
ListView list;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://........................";
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion > android.os.Build.VERSION_CODES.FROYO) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
}
/*
int images[] = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d};
*/
list = (ListView) findViewById(R.id.listView1);
accessWebService();
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar=new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
myPd_bar.dismiss();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
//build hash set for list view
public void ListDrwaer(){
List<String> listImg = new ArrayList<String>();
try{
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for(int i = 0; i<jsonMainNode.length();i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
listImg.add(img_url);
// Log.d("URL", img_url);
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(), listImg);
list.setAdapter(adapter);
}
catch(JSONException e){
Toast.makeText(getApplicationContext(),"Connection Error...", Toast.LENGTH_LONG).show();
}
}
}
Adapter class
package com.example.imagelist;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class ItemsAdapter extends ArrayAdapter<Integer> {
private final Context context;
ImageView imageView;
List<String> listImg;
ItemsAdapter(Context context, List<String> listImg) {
super(context, R.layout.items_list_item);
this.context = context;
this.listImg = listImg;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listImg.size();
}
#Override
public Integer getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final String text = listImg.get(position);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = convertView;
if (null == convertView)
rowView = inflater.inflate(R.layout.items_list_item, parent, false);
imageView = (ImageView) rowView.findViewById(R.id.list_item_image);
Bitmap bitmap;
URL imageURL = null;
try {
imageURL = new URL(text);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return rowView ;
}
}
activity_main.xml
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
list_item.xml
<ImageView
android:id="#+id/list_item_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
you can use gridView instead of listview.
Use onPreExecute and onPostExecute method
I want to post data using JSON. But i am not able to achieve this.
This is my java code:
package com.bandapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class UpcomingShow extends ListActivity {
public static final String TAG_SHOW_TITLE = "show_title";
public static final String TAG_SHOW_VENUE = "show_venue";
public static final String TAG_SHOW_DATE = "show_date";
public static final String TAG_SHOW_TIME = "show_time";
public static String URL = "http://example.com/example/example/mainAPI.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upcoming_show);
new AsyncData().execute();
}
class AsyncData extends AsyncTask<String, Void, Void> {
JSONParser jParser;
ArrayList<HashMap<String, String>> upcomingShows;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(UpcomingShow.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
jParser = new JSONParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
upcomingShows = new ArrayList<HashMap<String,String>>();
params.add(new BasicNameValuePair("rquest", "={"));
params.add(new BasicNameValuePair("method","band_info"));
params.add(new BasicNameValuePair("body","[{}]}"));
String res = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
res = EntityUtils.toString(response.getEntity());
JSONTokener t = new JSONTokener(res);
JSONArray a = new JSONArray(t);
JSONObject o = a.getJSONObject(0);
String sc = o.getString(TAG_SHOW_TITLE);
if(sc.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(UpcomingShow.this, upcomingShows, R.layout.upcomingshows_row, new String[] {
TAG_SHOW_TITLE, TAG_SHOW_DATE, TAG_SHOW_TIME, TAG_SHOW_VENUE }, new int[] { R.id.textTitle, R.id.textdate,
R.id.textTime, R.id.textVenue });
setListAdapter(adapter);
}
}
}
Also i am not able to Toast any of the message that i have kept in doInBackground(). Can you please help me solving this please...
You can't toast into doInBackground() because you can't update the UIview during the thread execution ! You should to use 'onProgress' and 'publishProgress'
change :
class AsyncData extends AsyncTask<String, Void, Void>
to:
class AsyncData extends AsyncTask<String, String, Void>
and override onProgress for toast:
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (values[0] != null)
Toast.makeText(UpcomingShow.this, values[0], Toast.LENGTH_SHORT).show();
}
And into doInBackground():
if(sc.equals("1"))
{
publishProgress(sc);
}
else
{
publishProgress("Fail.");
}
if(sc.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
Remove this code form doInBackground
You can not update your UI on do in background , you can get result in onPostExecute and able to pop up those toast .
I tried sending a post your request through Postman(google extension) and the URL you've provided responded with HTTP Status 200 but without a response message. Problem is, based on the code provided, is that you're expecting a message response from the said url. You should probably check with the server you are connecting with.
While doing AsyncTask<String, Void, Void> Task you can’t achieve Toast display in Main thread, user Log.d(“TAG”,”your-text”);
You can achieve Toast in onPostExecution()
}catch (Exception e)
{
e.printStackTrace();
}
return sc;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
if(result.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, result, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
}
}