Parse Json Object in android? - java

I am developing one application in that i have to receive data from server ,I am successfully read data . here i have problem i receive data from server code wrote in AsyncTask,and send data from AsyncTask to My activity,here i send only one data out of three,my json object have 3 objects.i can get 3 objects in AsyncTask but not getting in Activity
my AsyncTask
public class ReceivingLatLongAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
Context mContext;
JSONArray jsonArryDetails=null;
public static final String DETAILS = "locations";
public static final String LAT = "lat";
public static final String LNG = "lng";
public static final String ADDRESS = "address";
public static final String CTIME = "ctime";
private String lat1;
private String lng1;
private String address1;
private String time1;
public ReceivingLatLongAsync(Context context){
this.mContext = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ServiceHandler serviceHandler= new ServiceHandler();
String jSonString = `serviceHandler.makeServiceCall
(TrafficConstants.RECIEVE_LATLON_POL_URL, ServiceHandler.POST);`
Log.e("Response: ", "> " + jSonString);
if(jSonString != null){
try {
JSONObject jsonObject = new JSONObject(jSonString);
jsonArryDetails = jsonObject.getJSONArray(DETAILS);
for(int i = 0;i<jsonArryDetails.length();i++){
JSONObject mapDetails =
jsonArryDetails.getJSONObject(0);
lat1 = mapDetails.getString(LAT);
lng1 = mapDetails.getString(LNG);
address1 = mapDetails.getString(ADDRESS);
time1 = mapDetails.getString(CTIME);
Log.e("ADDRESS1", address1);
Log.e("TIME2",time1);
}
} 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);
pDialog.dismiss();
Intent intent = new Intent(mContext,GetLatLongForTPActivity.class);
intent.putExtra("LAT", lat1);
intent.putExtra("LNG", lng1);
intent.putExtra("ADDRESS", address1);
intent.putExtra("time",time1);
mContext.startActivity(intent);
}
}
my activty
public class GetLatLongForTPActivity extends FragmentActivity
implements LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_lat_long_for_tp);
timeEdit = (EditText)findViewById(R.id.timeId);
submitBtn = (Button)findViewById(R.id.subId);
Intent intent = getIntent();
String anotherLAT=intent.getStringExtra("LAT");
String anotherLNG=intent.getStringExtra("LNG");
Log.e(" NEW LATLONG",anotherLAT);
}

Becouse it is an jsonArray and now you send only the last object not the entier array

Change this
JSONObject mapDetails =
jsonArryDetails.getJSONObject(0);
to
JSONObject mapDetails =
jsonArryDetails.getJSONObject(i);
You have to add something like
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
for(int i = 0;i<jsonArryDetails.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject mapDetails =
jsonArryDetails.getJSONObject(i);
lat1 = mapDetails.getString(LAT);
lng1 = mapDetails.getString(LNG);
address1 = mapDetails.getString(ADDRESS);
time1 = mapDetails.getString(CTIME);
map.put(LAT, lat1);
map.put(LNG, lg1);
map.put(ADDRESS, address1 );
map.put(CTIME, time1 );
mylist.add(map);
}

In for loop change the index :
for(int i = 0;i<jsonArryDetails.length();i++){
JSONObject mapDetails =jsonArryDetails.getJSONObject(i);
//etc ^ //change here

You need to create a class that stores the four fields you are using (lat,long,address,time), make that object parable, you could use this example: http://aryo.lecture.ub.ac.id/android-passing-arraylist-of-object-within-an-intent/ ;
And after that you can attach the array to the intent using:
intent.putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)
This would be the correct way to handle this, even if it's a little more complicated then you originally would have hoped.

Related

getting a error with my code private void update list everything from "this, mCommentList" is underlined in red

Could someone help me. I was following a very long tutorial and got to the end and can't fix this error. Starting at public void update list the code below is underlined in red and I can't seem to correct the problem.
public class readComments extends ListActivity {
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://120.120.1.100 /webservice/comments.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_comments);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v)
{
Intent i = new Intent(readComments.this, AddComment.class);
startActivity(i);
}
public void updateJSONdata() {
}
private void updateList() {
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(readComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//Problem starts here everything underlined in red
#Override
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[]{TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME}, new int[]{R.id.title, R.id.message,
R.id.username});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}

how to display details of single item of list in another activity from url (json data)?

I have written a program to display the list of json data from a url which has an image and 5 textviews which is displaying perfectly.
Url : https://itunes.apple.com/search?term=jack+johnson&limit=50.
When i click on an item from the list i want to display the details of that item in another activity based on the track-id
Url : https://itunes.apple.com/lookup?id=659234741
So when i click on the item the details are getting displayed in the textview , but by default it is displaying the details of id = 659234741 for some items or in short the details does not match.
Need some help to figure out the problem
My Code :
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultsList = new ArrayList<HashMap<String, String>>();
lv = getListView();
// Calling async task to get json
new GetTunesDetails().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetTunesDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
tunes = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tunes.length(); i++) {
JSONObject c = tunes.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
resultsList.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, resultsList);
// Set the adapter to the ListView
lv.setAdapter(adapter);
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
int position;
TextView wrapperType, artistName, collectionName, trackName,
collectionPrice;
ImageView artworkImage;
public ListViewAdapter(Context context, ArrayList<HashMap<String, String>>
arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
// this.position = position;
inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.custom_row, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
wrapperType = (TextView) itemView.findViewById(R.id.wrapperType);
artistName = (TextView) itemView.findViewById(R.id.artistName);
collectionName = (TextView) itemView.findViewById(R.id.collectionName);
trackName = (TextView) itemView.findViewById(R.id.trackName);
collectionPrice = (TextView)
itemView.findViewById(R.id.collectionPrice);
// Locate the ImageView in listview_item.xml
artworkImage = (ImageView) itemView.findViewById(R.id.artworkImage);
// Capture position and set results to the TextViews
wrapperType.setText(resultp.get(MainActivity.TAG_WRAPPER_TYPE));
artistName.setText(resultp.get(MainActivity.TAG_ARTIST_NAME));
collectionName.setText(resultp.get(MainActivity.TAG_COLLECTION_NAME));
trackName.setText(resultp.get(MainActivity.TAG_TRACK_NAME));
collectionPrice.setText(resultp.get(MainActivity.TAG_COLLECTION_PRICE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.TAG_ARTWORK_IMAGE),
artworkImage);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { // TODO Auto-generated method
Toast.makeText(context, "Clicked at position " + position,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, SingleTrack.class);
intent.putExtra("track_image",
resultp.get(MainActivity.TAG_ARTWORK_IMAGE));
intent.putExtra("wrapper_type",
resultp.get(MainActivity.TAG_WRAPPER_TYPE));
intent.putExtra("artistName",
resultp.get(MainActivity.TAG_ARTIST_NAME));
intent.putExtra("collectionName",
resultp.get(MainActivity.TAG_COLLECTION_NAME));
intent.putExtra("trackName",
resultp.get(MainActivity.TAG_TRACK_NAME));
intent.putExtra("collectionPrice",
resultp.get(MainActivity.TAG_COLLECTION_PRICE));
intent.putExtra("trackId",
resultp.get(MainActivity.TAG_TRACK_ID));
context.startActivity(intent);
}
});
return itemView;
}
SingleTrack.java : This is the class where i displaying the details on single item click
public class SingleTrack extends Activity {
// URL to get contacts JSON
private static String url = "";
// JSON Node names
static final String TAG_RESULT = "results";
static final String TAG_ARTWORK_IMAGE = "artworkUrl100";
static final String TAG_WRAPPER_TYPE = "wrapperType";
static final String TAG_ARTIST_NAME = "artistName";
static final String TAG_COLLECTION_NAME = "collectionName";
static final String TAG_TRACK_NAME = "trackName";
static final String TAG_COLLECTION_PRICE = "collectionPrice";
static final String TAG_TRACK_ID = "trackId";
// contacts JSONArray
JSONArray tracks = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> singleTrackDetails;
ProgressDialog pDialog;
String passedData1, passedData2, passedData3, passedData4, passedData5,
passedData6, passedData7;
TextView wrapperTypeText, artistNameText, collectionNameText, trackNameText,
collectionPriceText;
ImageView trackImage;
String artworkImage, wrapperType, artistName, collectionName, trackName,
collectionPrice, trackId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_track);
wrapperTypeText = (TextView) findViewById(R.id.wrapperType1);
artistNameText = (TextView) findViewById(R.id.artistName1);
collectionNameText = (TextView) findViewById(R.id.collectionName1);
trackNameText = (TextView) findViewById(R.id.trackName1);
collectionPriceText = (TextView) findViewById(R.id.collectionPrice);
trackImage = (ImageView) findViewById(R.id.artworkImage1);
passedData1 = getIntent().getStringExtra("track_image");
passedData2 = getIntent().getStringExtra("wrapper_type");
passedData3 = getIntent().getStringExtra("artistName");
passedData4 = getIntent().getStringExtra("collectionName");
passedData5 = getIntent().getStringExtra("trackName");
passedData6 = getIntent().getStringExtra("collectionPrice");
passedData7 = getIntent().getStringExtra("trackId");
singleTrackDetails = new ArrayList<HashMap<String, String>>();
// url
url = "https://itunes.apple.com/lookup?id=" + passedData7;
// Calling async task to get json
new GetSingleTrackDetails().execute();
}
class GetSingleTrackDetails extends AsyncTask<String, Void, String> {
private JSONObject jsonObj;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SingleTrack.this);
pDialog.setMessage("Loading Track Details...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
tracks = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tracks.length(); i++) {
JSONObject c = tracks.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
singleTrackDetails.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
wrapperTypeText.setText(wrapperType);
artistNameText.setText(artistName);
collectionNameText.setText(collectionName);
trackNameText.setText(trackName);
collectionPriceText.setText(collectionPrice);
}
}
Thank you
The problem is that you are initializing the resultp each element in your getView method, so therefore the last id/element of the listview adapter's data will be considered as the resultp.
Im sure that the id 659234741 is the last element, which will always be the id for each onclick that would happen.
A solution for this is to create a final resultp within your getView method instead of having just one global resultp.
final HashMap<String, String> resultp = data.get(position);

ANDROID: Filter Listview data from PHP JSON using LAZYLIST

Im currently developing a mobile ordering app, and im using listview from https://github.com/thest1/LazyList for the summary of my orders but my problem is that all data of ORDERS from my database (Mysql) is showing.
I want to show only the orders per Customer ID
heres the sample image
-- > http://postimg.org/image/dnayd433x/
OrderSum.java
**OrderSum.java
public class OrderSum extends Activity{
ListView list;
TextView id; //// ver - id
TextView name; //// name - name
TextView quan; //// api - desc
TextView price; //// price
TextView order_num; //// price
TextView cust_num; //// price
ImageView image;
TextView items;
TextView empty;
TextView home_ornum;
TextView cust_name;
ImageButton addOrder;
ImageButton proceed;
DigitalClock time;
TextView os;
TextView o_total;
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
LvOrderSumAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID = "id";
static String NAME = "ord_name";
static String PRICE = "ord_price";
static String QTY = "ord_qty";
static String CUSTID = "customer_id";
static String ORDER = "ord_num";
static String PXQ = "price_x_quan";
static String IMAGE = "image";
static String OR = "text_ordernumber";
static String ON = "text_name";
static String TP = "t_price";
///////////////////////
#SuppressLint({ "SimpleDateFormat", "NewApi" })
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.order_summary);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
/**Unique ID / Customer Id***/
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
/**
* Hashmap to load data from the Sqlite database
**/
HashMap user = new HashMap();
user = db.getUserDetails();
final TextView unique_id = (TextView) findViewById(R.id.o_custnum);
unique_id.setText((CharSequence) user.get("uid"));
/**END**/
/** DATE VIEW***/
TextView h_date = (TextView) findViewById(R.id.o_date);
Calendar c = Calendar.getInstance();
SimpleDateFormat format1;
format1 = new SimpleDateFormat("MMMM dd,yyyy");
// format2 = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
h_date.setText(format1.format(c.getTime()) );
/** END DATE VIEW***/
cust_name = (TextView) findViewById(R.id.DisplaycustName);
home_ornum = (TextView) findViewById(R.id.Displayordernum);
time = (DigitalClock) findViewById(R.id.o_time);
Intent myIntent = getIntent();
home_ornum.setText(myIntent.getStringExtra("text_ordernumber")); //order number is the TextView
cust_name.setText(myIntent.getStringExtra("text_name")); //tv is the TextView
items= (TextView) findViewById(R.id.DisplayTotalItems);
/***************Custom Font***/
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/MavenPro.otf");
cust_name.setTypeface(myCustomFont);
home_ornum.setTypeface(myCustomFont);
time.setTypeface(myCustomFont);
h_date.setTypeface(myCustomFont);
/***************Custom Font**************/
addOrder = (ImageButton) findViewById(R.id.btn_add);
addOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(OrderSum.this,
Categories.class);
startActivity(myIntent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
});
/***************************PROCEED BUTTON***************************/
proceed = (ImageButton) findViewById(R.id.btn_proceed);
proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(OrderSum.this,
OrderInformation.class);
startActivity(myIntent);
// uniq id , order no , date , name
// final TextView d_date = (TextView) findViewById(R.id.o_date);
Intent ord_in = new Intent ( OrderSum.this, OrderInformation.class );
ord_in.putExtra ( "text_order", home_ornum.getText().toString() );
// ord_in.putExtra ( "text_date", d_date.getText().toString() );
ord_in.putExtra ( "text_custName", cust_name.getText().toString() );
ord_in.putExtra ( "text_items", items.getText().toString() );
startActivity(ord_in);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
});
/***************************PROCEED BUTTON***************************/
/**for the ROOF2**/
final ActionBar actionBar = getActionBar();
BitmapDrawable background = new BitmapDrawable
(BitmapFactory.decodeResource(getResources(), R.drawable.roof2));
///background.setTileModeX(android.graphics.Shader.TileMode.REPEAT);
actionBar.setBackgroundDrawable(background);
/**end for the ROOF2**/
} /// end of OnCreate
#Override
public void onBackPressed() {
super.onBackPressed();
/*Intent myIntent = new Intent(OrderSum.this,
Home.class);
startActivity(myIntent);*/
TextView on = (TextView) findViewById(R.id.Displayordernum);
Intent home_in = new Intent ( OrderSum.this, Home.class );
home_in.putExtra ( "text_ordernumber", on.getText().toString() );
startActivity(home_in);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(OrderSum.this);
// Set progressdialog title
mProgressDialog.setTitle("Your orders");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
TextView custname = (TextView) findViewById(R.id.DisplaycustName);
TextView homeornum = (TextView) findViewById(R.id.Displayordernum);
Intent home_in = getIntent();
homeornum.setText(home_in.getStringExtra("text_ordernumber")); //tv is the TextView
custname.setText(home_in.getStringExtra("text_name")); //name is the TextView
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
JSONObject jsonobject = JSONfunctions.getJSONfromURL("http://192.168.43.52/MMOS/api/ordershow.php") ;
// jsonobject = JSONfunctions.getJSONfromURL( //192.168.43.52 /// 10.0.2.2
// ordershow, "GET", params);
//jsonobject = JSONfunctions.getJSONfromURL(,)
try {
// Locate the array name in JSON==
jsonarray = jsonobject.getJSONArray("orders");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
/* from db orders = id,ord_name,ord_desc,
ord_price,ord_qty,customer_id,ord_num,price_x_quan , image jsonobjecy = from db*/
map.put("id", jsonobject.getString("id"));
map.put("ord_name", jsonobject.getString("ord_name"));
map.put("ord_price", jsonobject.getString("ord_price"));
map.put("ord_qty", jsonobject.getString("ord_qty"));
map.put("customer_id", jsonobject.getString("customer_id"));
map.put("ord_num", jsonobject.getString("ord_num"));
map.put("price_x_quan", jsonobject.getString("price_x_quan"));
map.put("image", jsonobject.getString("image"));
map.put("text_ordernumber",home_in.getStringExtra("text_ordernumber"));
map.put("text_name",home_in.getStringExtra("text_name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listOrderSummary);
// Pass the results into ListViewAdapter.java
adapter = new LvOrderSumAdapter(OrderSum.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.getAdapter().getCount();
String count = ""+listview.getAdapter().getCount();
items.setText(count);
// Close the progressdialog
mProgressDialog.dismiss();
}
} **
and for the JSONFUNCTION
** public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
and the PHP CODE
<?php
mysql_connect('localhost','root','')or die ('No Connection');
mysql_select_db('dbmoms');
//$o_od = $_GET['text_ordernumber'];
$sql ="SELECT * FROM orders"; // WHERE ord_num ='$o_od' "; //WHERE ord_num = '$ordnum'
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$arr['orders'][]= $row;
}
$json = json_encode($arr);
$json_encoded_string = json_encode($arr);
$json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
echo $json_encoded_string;
?>
I hope that you can help me :)
thanks in advance. :)

How to put 2 parameters in doInBackground asynctask ?

I use Asynctask to load and get data from php. And I have to pass 2 parameters to php.
But I don't know how.
Here is the java code :
public class info extends Activity{
ProgressDialog pDialog;
TextView movie_tittle, studio, date;
int std;
String movie, reservation, ttl, dt;
private String URL_CATEGORIES = "http://10.0.2.2/cinemainfo/info.php";
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> accountsList;
JSONArray accounts = null;
private static final String TAG_SUCCESS = "success";
private static final String TAG_ACCOUNT = "message";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
movie = getIntent().getStringExtra("kode_intent");
reservation = getIntent().getStringExtra("kode_intent2");
movie_tittle=(TextView)findViewById(R.id.tv_tittle);
date=(TextView)findViewById(R.id.tv_date);
studio=(TextView)findViewById(R.id.tv_studio);
new GetCategories().execute();
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(info.this);
pDialog.setMessage("Please Wait..");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("id_movie", movie));
params.add(new BasicNameValuePair("id_reservation", reservation));
JSONObject json = jParser.makeHttpRequest(URL_CATEGORIES, "GET", params);
Log.d("All Accounts: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
accounts = json.getJSONArray(TAG_ACCOUNT);
for (int i = 0; i < accounts.length(); i++) {
JSONObject json_data = accounts.getJSONObject(i);
ttl=json_data.getString("movie_tittle");
dt=json_data.getString("date");
std = json_data.getInt("studio");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
result();
}
}
private void result() {
try{
movie_tittle.setText(ttl);
date.setText(dt);
studio.setText(String.valueOf(std));
}
catch(Exception e){
Log.e("log_tag","Error in Display!" + e.toString());;
}
}
}
I want to pass id_movie and id_reservation to php code..Both is getting from movie = getIntent().getStringExtra("kode_intent"); and reservation = getIntent().getStringExtra("kode_intent2");
But when I run the code in emulator, It displays nothing..The php code is fine..But I'm not sure with my java code. How to pass 2 parameters in doInBackground asynctask? Did I do something wrong ?
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list
And change your async task implementation
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> passed = passing[0]; //get passed arraylist
//Some calculations...
return result; //return result
}
protected void onPostExecute(ArrayList<String> result) {
dialog.dismiss();
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
}
Calling:
String[] arrayOfValue = new String[2];
arrayOfValue[0] = movie;
arrayOfValue[1] = reservation;
new GetCategories().execute(arrayOfValue);
Usage:
protected ArrayList<String> doInBackground(String... passing){
String movie = passing[0];
String reservation = passing[1];
}

Where do I put the function to display the loading process?

I want to display a loading process when my application is loading data from the database.
This is my Java file.
Where do I have to put the function to display the loading process?
public class AksesServerActivity extends ListActivity {
private static String link_url = "http://plnskh.zz.mu/android/berita/cekdaftar.php";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, daftar_artikel,
R.layout.list_item,
new String[] { AR_JUDUL, AR_CONTENT, AR_ID}, new int[] {
R.id.judul, R.id.content, R.id.kode});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String kode = ((TextView) view.findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(AksesServerActivity.this, DetailAksesServer.class);
in.putExtra(AR_ID, kode);
startActivity(in);
}
});
}
}
public class LongOperation extends AsyncTask<String, String, String>
{
ProgressDialog pdialog;
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pdialog.dismiss();
this.adapter_listview();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(NewsActivity.this);
pdialog.setMessage("Loading");
pdialog.show();
}
}
for more clarification about asynchronous task and its methods, check here
You must use AsyncTask class, override doInBackground method to perform your databse fetch, onPreExecute method to show your loading and onPostExecute to hide it. you can refer AsynTask process and AsynTask post for more information

Categories

Resources