Android: connecting mysql(XAMPP) to android app on emulator - android

I'm trying to develop an android application for my final year project and i'm at the point where I need to connect a database to my application. I have previously connected to internal and external SQLite database but my supervisor says that I must use the XAMPP localhost so it would be justifiable later as it is very similar to a real life situation where a web server would be used.
Here is the code for my DBHelper class, that i adapted from a sample code I found over the net and did change a few things but i'm quite sure there is a ton of errors.
When the button to view the data, which would lead to this class is pressed, it would just show a blank screen and after a long while would crash.
package com.example.parking_guide;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class DBHelper extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static final String url_all_products = "http://10.0.0.2/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String KEY_ROWID = "_id";
private static final String KEY_VACANT = "vacancy";
// products JSONArray
JSONArray table = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView yourListView = getListView();
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("Level1: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
table = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < table.length(); i++) {
JSONObject c = table.getJSONObject(i);
// Storing each json item in variable
String _id = c.getString(KEY_ROWID);
String vacant = c.getString(KEY_VACANT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ROWID, _id);
map.put(KEY_VACANT, vacant);
// adding HashList to ArrayList
productsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
DBHelper.this, productsList,
R.layout.list_item, new String[] { KEY_ROWID,
KEY_VACANT},
new int[] { R.id.id, R.id.vac});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
So i don't really know what's wrong as i'm not that good at android and just learning as I go on. Anyone who can help me?

You should use 10.0.2.2 to acces your localhost, not 10.0.0.2 :)
http://developer.android.com/tools/devices/emulator.html#networkaddresses

Related

How to Set ImageView in AsyncTask

I understand that we cannot set ImageView in AsyncTask. But I need to add the ImageView into HashMap and the HashMap need to add into an ArrayList inside the for loop. I cannot do that in onPostExecute(). Does anyone know how to do?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.1.132/retEqp.php";
ImageView iv;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "equipments";
private static final String TAG_PID = "item_ID";
private static final String TAG_NAME = "item_Name";
private static final String TAG_DESC = "item_Desc";
private static final String TAG_LOC = "item_Location";
private static final String TAG_STATUS = "item_Status";
private static final String TAG_IMAGE = "item_Image";
// products JSONArray
JSONArray equipments = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
iv = (ImageView)findViewById(R.id.img2);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent previousScreen = new Intent(getApplicationContext(), NewProductActivity.class);
//Sending the data to NewProductActivity
previousScreen.putExtra("id",pid);
setResult(1000, previousScreen);
finish();
// starting new activity and expecting some response back
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
// Log.d("All Products: ", json.toString());
try {
equipments = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < equipments.length(); i++) {
JSONObject c = equipments.getJSONObject(i);
// Storing each json item in variable
String id = "ID: "+c.getString(TAG_PID);
String name = "Name: "+c.getString(TAG_NAME);
String desc = "Description: "+c.getString(TAG_DESC);
String loc = "Location: "+c.getString(TAG_LOC);
String status = "Status: "+c.getString(TAG_STATUS);
String image = c.getString(TAG_IMAGE);
byte[] rawImage = Base64.decode(image, Base64.DEFAULT);
Bitmap bmp12 = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
iv.setImageBitmap(bmp12);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_IMAGE, rawImage.length);
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESC, desc);
map.put(TAG_LOC, loc);
map.put(TAG_STATUS, status);
map.put(TAG_IMAGE, iv.toString());
// adding HashList to ArrayList
productsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_IMAGE,TAG_PID,
TAG_NAME,TAG_DESC,TAG_LOC,TAG_STATUS},
new int[] {R.id.img,R.id.pid, R.id.name,R.id.desc,R.id.loc,R.id.status});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can't access the UI in a background thread.
The idea behind AsyncTask is that doInBackground does the background work, then you can return something that will be passed as a parameter to onPostExecute which is executed in the main thread.
In this case you have to return the parsed model objects from doInBackground (I would create a custom class), receive in onPostExecute. Also, create a custom adapter, which will take care of creating views. You should generate bitmaps there (probably you have to put the parsing to bitmap in another async task).

Not sure how to get data from each element of a list to download and display images in it from async task

G'day guys!
I'm trying to work out a good approach to download pictures and update a user list with the picture once it has finished downloading.
So I'm trying to create a list of user profiles in an android app, where it displays their username and a little picture at the side of them. I've been watching tutorials for the last 2 weeks and slowly getting a feel for all thing android, and I have my app pulling data down from my SQL (via PHP) server without issue, BUT I'm having trouble working out how and where I can launch an asynchronous task to download a picture for each username.
I'm thinking something along the lines of flow like this
User clicks refresh button to
App talks to PHP on webserver and pulls down list of users (does this correctly so far)
Parse all the data from the server that it got and turn it into a list (does this correctly so far)
Data in the list contains URL for profile picture (does this correctly)
Go through each list element one by one and begin async task to download picture (don't know how to go element by element to extract URL from list)
Once picture is downloaded then display it (as above, don't know how to update each element)
The behavior is sort of inspired off the "Reddit is Fun" app, whereby all the articles are displayed and preview images are loaded and displayed as they are downloaded. You see a little spinning circle as a placeholder until the image is seen.
package com.example.administrator.hellopants;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class UserlistActivity extends Activity{
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> allUserList;
private static String url_all_users = "http://myurl.com/php/db_list_all_users.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERLIST = "userlist";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
JSONArray userlist = null;
Button buttonRefresh;
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_userlist);
allUserList = new ArrayList<HashMap<String,String>>();
buttonRefresh = (Button) findViewById(R.id.button_refresh);
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new PopulateUserList().execute();
}
});
}
class PopulateUserList extends AsyncTask<String, String, String> {
ListView lvItems = (ListView) findViewById(R.id.listview_usernames);
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UserlistActivity.this);
pDialog.setMessage("Loading users details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params);
Log.d("All Usernames JSON Output: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userlist = json.getJSONArray(TAG_USERLIST);
// looping through All Products
for (int i = 0; i < userlist.length(); i++) {
JSONObject c = userlist.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_USERNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_USERNAME, name);
// adding HashList to ArrayList
allUserList.add(map);
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
UserlistActivity.this, allUserList,
R.layout.list_userliststyle, new String[] { TAG_ID,
TAG_USERNAME},
new int[] { R.id.list_userliststyle_id, R.id.list_userliststyle_username });
// updating listview
lvItems.setAdapter(adapter);
}
});
}
}
public class DownloadImageBackground extends AsyncTask<String, Void, Drawable> {
ImageView imageView;
String myURL = null;
#Override
protected Drawable doInBackground(String...strings) {
this.myURL = strings[0];
Log.i("doInBackground", "Loading image from: "+ myURL.toString());
//TODO: Pass the correct URL to download_image
return download_Image(myURL);
}
#Override
protected void onPostExecute(Drawable result) {
imageView.setImageDrawable(result);
}
private Drawable download_Image(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, url);
return d;
} catch (Exception e) {
Log.e("download_Image", "Caught exception: "+e.getMessage());
return null;
}
}
}
}
Okie thanks to Nasch, that seemed to help prod me in the right direction
String username = allUserList.get(0).get(TAG_USERNAME);
Log.d("And the winner is", username);
And thus the username string is printed out. To do that with a URL is probably similar, but my main problem was trying to work out how to pull data out from the list and that seems to have been solved now :D (finally after 3 days, phew)
Had a feeling it would be something simple that I couldn't figure out.

problems with ProgressDialog,RunOnUiThread and ListAdapter

Ok i've written this android program that has 3 tabs(MEALS,DRINKS AND DESSERT) each in its own activity with a fragment.The problem i'm having now is with retrieving the list from a mysql database and displaying this list in each tab.I'de already ran and executed a custom code which displays a list of items retrieved from a mysql database in a single list,which worked fine.Now bringing this code to my program gives me 3 errors
1)
pDialog = new ProgressDialog(MealsFragment.this); which says
ProgressDialog(android.context,Context) in progressDialog cannot be applied to
com.example.tab.tablayout.MealsFragment
2)
runOnUiThread(new Runnable() which says "cannot resolve method runonuithread "
3)is all about the list adapter.
The initial code used OnCreate,but my fragment uses oncreateView.I dont know if thats the issue.
Here is the code for the MealsFragment.java
package com.example.tabs.tablayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
/**
* Created by GIGABYTE on 5/21/2014.
*/
public class MealsFragment extends ListFragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> mealsList;
// url to get all products list
private static String url_all_meals = "http://10.180.79.73/dbase_connect/get_all_meals.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MEALS = "meals";
private static final String TAG_MID = "mid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray meals = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_meals, container, false);
// Hashmap for ListView
mealsList = new ArrayList<HashMap<String, String>>();
// Loading meals in Background Thread
new LoadAllMeals().execute();
// Get listview
ListView lv = getListView();
return rootView;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllMeals extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MealsFragment.this);
pDialog.setMessage("Loading Meals. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All Meals from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_meals, "GET", params);
// Check your log cat for JSON response
Log.d("All Meals: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Meals found
// Getting Array of Meals
meals = json.getJSONArray(TAG_MEALS);
// looping through All meals
for (int i = 0; i < meals.length(); i++) {
JSONObject c = meals.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_MID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
mealsList.add(map);
}
} /*else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
*/
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all meals
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MealsFragment.this, mealsList,
R.layout.meals_list_item, new String[] {TAG_MID,
TAG_NAME},
new int[] { R.id.mid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
1) The first parameter of the ProgressDialog constructor must be a context. Use
new ProgressDialog(getActivity());
2) You could use getActivity().runOnUiThread(...). However, that's not necessary in this context. The AsyncTask.onPostExecute() method is already running in the UI thread. Just move the Runnable code into the body of the onPostExecute() method.
3) Same as 1, first parameter must be a context. Use new SimpleAdapter(getActivity(), ...).

Getting values from database and displaying in Text Views

I am working on an android application.I want to fetch data from my database and display it in the textview. I am using Mysql server. mylay.xml is the name of my xml file which contains three textviews. In my code i am manually passing some string to the database and fetching record which matches with the string passed.
package com.example.festipedia_logo;
import java.util.ArrayList;
import java.util.HashMap;
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 com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.example.festipedia_logo.Searchpage.LoadAllProducts;
//import com.example.connection.disp;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class calledclass extends SherlockFragment {
ArrayAdapter<String> adapter;
String[] city;
// Progress Dialog
private ProgressDialog pDialog;
String nameeve;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
JSONArray products = null;
EditText b;
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
// private static String url_all_products = "http://192.168.43.185:8080/festipedia/get_product_details.php";
private static String url_all_products = "http://192.168.43.185:8080/festipedia/myall.php";
Button a;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "product";
// products JSONArray
//JSONArray products = null;
TextView one;
TextView two;
TextView three;
String n,ll,m;
Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.second);
View rootView = inflater.inflate(R.layout.mylay, container, false);
// nameeve=getArguments().getString("message");
// setContentView(R.layout.all_products);
one = (TextView) rootView.findViewById(R.id.textView1);
two = (TextView) rootView.findViewById(R.id.textView2);
three = (TextView) rootView.findViewById(R.id.textView3);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
// Loading products in Background Thread
// new LoadAllProducts().execute();
return rootView;
// Get listview
//ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
}
// Response from Edit Product Activity
//#Override
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//List<NameValuePair> params = new ArrayList<NameValuePair>();
//Here i am sending some name gan to the database so that it returns the details where name is gan
params.add(new BasicNameValuePair("eventname", "gan"));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
// Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
//products = json.getJSONArray(TAG_PRODUCTS);
/*
JSONArray productObj = json
.getJSONArray(TAG_PRODUCTS); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0); */
JSONArray productObj = json
.getJSONArray(TAG_PRODUCTS); // JSON Array
// get first product object from JSON Array
JSONObject c = productObj.getJSONObject(0);
/*products = json.getJSONArray(TAG_PRODUCTS);
JSONObject c = products.getJSONObject(0);
*/
/* n = c.getString("eventname");
ll = c.getString("collegename");
m = c.getString("location");
*/
one.setText(c.getString("eventname"));
two.setText(c.getString("collegename"));
three.setText(c.getString("location"));
} else {
// no products found
// Launch Add New product Activity
}
} 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 got all details
pDialog.dismiss();
}
}
}
I think one problem is that your class extends with SherlockFragment so you need to use getSherlockActivity() instead of getActivity()
So change from here
pDialog = new ProgressDialog(getActivity());
to
pDialog = new ProgressDialog(getSherlockActivity());
and also other place at where you have used getActivity().
Also just declare global variable of
JSONParser jParser;
and not initialize it on onCreateView() method.
jParser = new JSONParser();

Android, Tab layout which has listfragment from json parsing

i'm trying to build android app which has tab layout which also has listfragment. i want total of three tabs, first home, second listview and third when clicked on listview it switches to third tabs and show some information all using json parsing.
i'm using this tutorials as a reference http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
and for listview i'm using following - http://www.androidhive.info/2012/10/android-multilevel-listview-tutorial/
Now the question is that how can i change listActivity to listFragment?
How can i turn this code from Listactivity to Listfragment?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.androidhive.helper.AlertDialogManager;
import com.example.androidhive.helper.ConnectionDetector;
import com.example.androidhive.helper.JSONParser;
public class AlbumsActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> albumsList;
// albums JSONArray
JSONArray albums = null;
// albums JSON url
private static final String URL_ALBUMS = "http://api.androidhive.info/songs/albums.php";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SONGS_COUNT = "songs_count";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
ListView lv = getListView();
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
// send album id to tracklist activity to get list of songs under that album
String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Albums ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String songs_count = c.getString(TAG_SONGS_COUNT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_SONGS_COUNT, songs_count);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, albumsList,
R.layout.list_item_albums, new String[] { TAG_ID,
TAG_NAME, TAG_SONGS_COUNT }, new int[] {
R.id.album_id, R.id.album_name, R.id.songs_count });
// updating listview
setListAdapter(adapter);
}
});
}
}
}

Categories

Resources