How to use GetJsonFromUrlTask.java in a fragment - java

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;
}
}
}

Related

I got error Android JSON parsing Retrieve from URL

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"));

How to handle Login Successful in json? [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to implement login and signup form in Android with the help of JSON using post method. When i signup and enter the details it successfully register and data has been shown in my local host sever and when i login its enter wrong username and password its show incorrect details in toast and enter right details shows login success in toast, but i want when i enter right details its goes to another activity. and enter wrong details shows only toast. Here is the code :-
MainActivity.java
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
private static final String TAG = "LoginActivity";
String URL = "http://10.0.2.2/test_android/index.php";
JSONParser jsonParser=new JSONParser();
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, password;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
password = (EditText)findViewById(R.id.passwordd);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptLogin attemptLogin = new AttemptLogin();
attemptLogin.execute(username.getText().toString(), password.getText().toString(), "");
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private class AttemptLogin extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
String email = args[2];
String password = args[1];
String name = args[0];
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", name));
params.add(new BasicNameValuePair("password", password));
if (email.length() > 0)
params.add(new BasicNameValuePair("email", email));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
static String error = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
ArrayList<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.e("API123", " " +convertStreamToString(httpPost.getEntity().getContent()));
Log.e("API123",httpPost.getURI().toString());
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("API123",""+httpResponse.getStatusLine().getStatusCode());
error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equals("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();
Log.d("API123",json);
} 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);
jObj.put("error_code",error);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
}
protected void onPostExecute(JSONObject result) {
try {
if (result != null)
{
if(result.getString("message").equals("Successfully logged in"))
{
Intent intent = new Intent(ThisActivity.this,NewActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from
server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Java Android Studio

I am new to Android, I followed some tutorials online to create a login page with MySQL database hosted locally on my PC.
I am getting an error on JSONParser.java file says:
Error:(60, 61) error: incompatible types: List<Pair<String,String>> cannot be converted to List<? extends NameValuePair>
Here is the code in JSONParser.java
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<Pair<String, String>> 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;
}
}
And here is for Login.java
public class login extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputUsername, inputPassword;
Button btnlogin;
TextView txtregister;
// url to login
private static String url_login = "http://10.0.2.2/VICOBA/login.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Edit Text
inputUsername = (EditText)findViewById(R.id.login_username);
inputPassword = (EditText)findViewById(R.id.login_password);
//Text View
txtregister = (TextView)findViewById(R.id.createAccount);
//Create button
btnlogin = (Button)findViewById(R.id.loginBtn);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Make login in background thread
String username = inputPassword.getText().toString();
String password = inputPassword.getText().toString();
new doLogin().execute(username,password);
}
});
}
/**
* Background Async Task to Create new product
* */
class doLogin extends AsyncTask<String, String, String>{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(login.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
//String description = inputDesc.getText().toString();
String username = args[0];
String password = args[1];
// Building parameters
List<Pair<String, String>> params = new ArrayList<>();
params.add(new Pair<>("username", username));
params.add(new Pair<>("password", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check log cat fro response
Log.d("Login", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} 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 done
pDialog.dismiss();
}
}
}
I have stacked here for some days trying searching for online solution with no success.

I want to display values on textview through JSONParser using given url

I want to display about_builder of given JSON url, but I am not able to declare properly JSONObject and JSONArray on MainActivity, so please anyone help me to display the data on TextView.
Error shown:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.and_ws_builder/com.example.and_ws_builder.MainActivity}:
android.os.NetworkOnMainThreadException
MainActivity.java class
public class MainActivity extends Activity {
private static String url ="http://myfourwalls.in/services_microsite/project_builder.php";
private static final String TAG_Name = "about_builder";
JSONArray builder = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFormUrl(url);
try {
builder = json.getJSONArray(TAG_Name);
JSONObject c = builder.getJSONObject(0);
for (int i = 0; i < json.length(); i++) {
String name = c.getString(TAG_Name);
final TextView nam = (TextView) findViewById(R.id.txtname);
nam.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFormUrl(String url) {
try {
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 {
jobj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parse","error Parsing data" + e.toString());
}
return jobj;
}
}
main_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtname"
android:layout_width="fill_parent"
android:layout_height="100dp"/>
</RelativeLayout>
You are using Network related code in main thread. Use AsyncTask.
You are calling network calls inside the main thread means foreground which is not supported in android.So use assynctask class which will handle network calls in background.
1)inside on create method call like:
new GetJson().execute();
2) declare the following outside oncreate
private class GetJson extends AsyncTask<String, Void, String> {
JSONObject c=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFormUrl(url);
try {
builder = json.getJSONArray(TAG_Name);
c = builder.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
return c;
}
#Override
protected void onPostExecute(final JSONObject result) {
for (int i = 0; i < result.length(); i++) {
String name = result.getString(TAG_Name);
final TextView nam = (TextView) findViewById(R.id.txtname);
nam.setText(name);
}
}

Why is the Progess Dialog appearing when back button is pressed?

When I go back to the previous activity by pressing the back button the progress dialog is appearing and not disappearing. When I minimize they the app the progress dialog disappears.
Here is the code for the async class
public class BackGroundTask extends AsyncTask<String, String, JSONObject> {
List<NameValuePair> postparams = new ArrayList<NameValuePair>();
private ProgressDialog pd;
String url = null;
String method = null;
Context context;
public BackGroundTask(String url, String method,
List<NameValuePair> params, Context context) {
this.url = url;
postparams = params;
this.method = method;
this.context = context;
//pd = new ProgressDialog(context);
//pd.setTitle("Processing...");
//pd.setMessage("Please wait.");
//pd.setCancelable(false);
//pd.setIndeterminate(true);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd = ProgressDialog.show(context, "Processing...", "Please wait.", true, false);
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pd.dismiss();
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if (method.equals("POST")) {
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
HttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams,
"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());
}
System.out.println(json);
// 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());
}
//pd.dismiss();
// return JSON String
return jObj;
}
}
You aren't dismissing it when you finish the Activity and the task must not be done. Override finish() and dismiss it if needed
#Override
public void finish()
{
if (pd.isShowing()
{
pd.dismiss();
}
super.finish();
}
You could also Override onBackPressed() and put this code there but since pressing the back button calls finish() its probably safer just to do it there.
Also, you are comparing Strings correctly in one place
if (method.equals("POST")) // correct
but not others
else if (method == "GET") // incorrect

Categories

Resources