Can not load data to ListView in Activity - java

I'm using json to load data in Activity class with content following as:
My Activity class:
public class CategoryCarActivity extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
ArrayList<Category> carsList = new ArrayList<Category>();
JSONArray manufacturers = null;
String manufacturer_id, manufacturer_name;
private static final String URL_MANUFACTURERS = "MyURL";
// ALL JSON node names
private static final String TAG_CARS = "cars";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MANUFACTURER = "name";
private static final String TAG_PRICE = "price";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(CategoryCarActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
Intent i = getIntent();
manufacturer_id = i.getStringExtra("id");
carsList = new ArrayList<Category>();
// Loading tracks in Background Thread
new LoadTracks().execute();
// get listview
ListView lv = getListView();
/**
* Listview on item click listener
* SingleTrackActivity will be lauched by passing manufacturer id, car id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
// On selecting single track get car information
Intent i = new Intent(getApplicationContext(), DetailListCarActivity.class);
// to get car information
// both manufacturer id and car is needed
String manufacturer_id = ((TextView) view.findViewById(R.id.manufacturer_id)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
Toast.makeText(getApplicationContext(), "Manufacturer Id: " + manufacturer_id + ", Car Id: " + car_id, Toast.LENGTH_SHORT).show();
i.putExtra("manufacturer_id", manufacturer_id);
i.putExtra("car_id", car_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all tracks under one album
* */
class LoadTracks extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CategoryCarActivity.this);
pDialog.setMessage("Loading selected car ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting tracks json and parsing
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// post album id as GET parameter
params.add(new BasicNameValuePair(TAG_ID, manufacturer_id));
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_MANUFACTURERS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Category List JSON: ", json);
try {
JSONObject jObj = new JSONObject(json);
if (jObj != null) {
String manufacturer_id = jObj.getString(TAG_ID);
manufacturer_name = jObj.getString(TAG_MANUFACTURER);
manufacturers = jObj.getJSONArray(TAG_CARS);
if (manufacturers != null) {
// looping through All cars
for (int i = 0; i < manufacturers.length(); i++) {
JSONObject c = manufacturers.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
// track no - increment i value
String track_no = String.valueOf(i + 1);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// creating new HashMap
// HashMap<String, String> map = new HashMap<String, String>();
Category category = new Category();
category.setManufacturer_id(manufacturer_id);
category.setId(id);
category.setName(name);
category.setPrice(price);
// adding each child node to HashMap key => value
/*
map.put("manufacturer_id", manufacturer_id); // note here
map.put(TAG_ID, car_id);
map.put("track_no", track_no + ".");
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
*/
// adding HashList to ArrayList
// carsList.add(map);
carsList.add(category);
}
} else {
Log.d("Manufacturers: ", "null");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
pDialog.dismiss();
ListAdapter adapter = new ArrayAdapter<Category>(
CategoryCarActivity.this, // the context
R.layout.list_item_categorys, // Simple list item - will toString() your data
carsList // The arraylist
);
// updating listview
setListAdapter(adapter);
}
}
}
list_item_categorys.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/manufacturer_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Song id / Hidden by default -->
<TextView
android:id="#+id/car_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/track_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:paddingLeft="5dip"
android:paddingTop="15dip"
android:textColor="#000000"
android:textSize="16dip"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/manufacturer_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:paddingLeft="5dip"
android:paddingTop="15dip"
android:textColor="#000000"
android:textSize="16dip"
android:layout_toRightOf="#+id/track_no"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:paddingLeft="3dip"
android:paddingRight="6dip"
android:textColor="#9ed321" />
I have debugged and check Logcat and see that data has loaded and everything normal, but don't know why data can not load to ListView
updated
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.totoroads.android.app, PID: 4697
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:393)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
How to fix this problem?? thank you

You're not providing your list to the list view. You need to add your list to your list view with an adapter. This tutorial should help walk you through the process. http://www.vogella.com/tutorials/AndroidListView/article.html
In your postExecute of your asyncTask you can than call adapter.notifyDataSetChanged(). And your view will update with the new list content.

This code looks really similar... maybe copy the rest of it?
You need an Adapter for your data.
protected void onPostExecute(String result) {
// dismiss the dialog after getting all tracks
pDialog.dismiss();
ListAdapter adapter = new ArrayAdapter<Category>(
CategoryCarActivity.this, // the context
android.R.layout.simple_list_item_1, // Simple list item - will toString() your data
carList // The arraylist
);
// updating listview
setListAdapter(adapter);
}
You can also make a subclass of ArrayAdapter<Category> if you really want to customize a layout.

Adding to Ben's answer, you need to set the list to the listview adapter after the asynctask completes its background functionality i.e in onPostExecute() method of the asynctask.

Need to set the list view as suggested by Ben in onPostExecute().
ListView listView = (ListView) findViewById(R.id.your_list_view_id);
listView.getAdapter().notifyDataSetChanged();

Related

Android crash in AsyncTask

When I run my projent and it's run AsyncTask from the activity that shows all content of the item the APP crash showing the follow error message:
06-17 20:56:52.856 418-428/? E/art﹕ Failed sending reply to debugger: Broken pipe
06-17 20:57:07.391 418-767/com.example.user.project_test E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
Process: com.example.user.project_test, PID: 418
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6357)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:909)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4690)
at android.view.View.invalidateInternal(View.java:11801)
at android.view.View.invalidate(View.java:11765)
at android.view.View.invalidate(View.java:11749)
at android.widget.TextView.checkForRelayout(TextView.java:6858)
at android.widget.TextView.setText(TextView.java:4057)
at android.widget.TextView.setText(TextView.java:3915)
at android.widget.TextView.setText(TextView.java:3890)
at com.example.user.project.itemActivity$getitem.doInBackground(itemActivity.java:132)
at com.example.user.project.itemActivity$getitem.doInBackground(itemActivity.java:84)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
06-17 20:57:07.612 418-418/com.example.user.project_test E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.project.itemActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{19feb64d V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at com.example.user.project.itemActivity$getitem.onPreExecute(itemActivity.java:96)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
at android.os.AsyncTask.execute(AsyncTask.java:539)
at com.example.user.project.itemActivity.onCreate(itemActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.description.invoke(Native description)
at java.lang.reflect.description.invoke(description.java:372)
at com.android.internal.os.ZygoteInit$descriptionAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I put here my current code
ItemActivity.java (it's the class that crash in AsyncTask:
public class ItemActivity extends AppCompatActivity {
private static final String TAG_SUCCESS = "success";
private static final String TAG_ITEM = "item";
private static final String TAG_ITEM_NAME = "name";
private static final String TAG_ITEM_description = "item";
Integer item_id;
String name;
String username;
String item;
TextView itemname;
TextView itemitem;
ProgressDialog pDialog;
JSONParser jParser;
RecyclerView recycler;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
Intent i = getIntent();
if (i.hasExtra("item_id")) {
Bundle bd = getIntent().getExtras();
/*if ((!bd.getString("name").equals(null) || bd.getString("name").trim().length() > 0) && (!bd.getString("username").equals(null) || bd.getString("username").trim().length() > 0) && (!bd.getString("description").equals(null) || bd.getString("description").trim().length() > 0)) {
name = bd.getString("name");
username = bd.getString("username");
description = bd.getString("description");
}*/
item_id = bd.getInt("item_id");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setTitle(R.string.app_name);
itemname = (TextView) findViewById(R.id.itemName);
itemdescription = (TextView) findViewById(R.id.itemDescription);
new getitem().execute();
/*recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);*/
}
/**
* Background Async Task to Get complete item details
*/
class getitem extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pDialog != null) {
pDialog = null;
}
pDialog = new ProgressDialog(itemActivity.this);
pDialog.setMessage(getResources().getString(R.string.loadingitem));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Getting item details in background thread
*/
protected String doInBackground(String... params) {
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> myParameters = new ArrayList<NameValuePair>();
myParameters.add(new BasicNameValuePair("item_id", Integer.toString(item_id)));
// getting item details by making HTTP request
// Note that item details url will use GET request
jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(AppConfig.URL_GET_item, "GET", myParameters);
// check your log for json response
Log.d("Single item Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received item details
JSONArray itemObj = json.getJSONArray(TAG_item); // JSON Array
// get first item object from JSON Array
JSONObject item = itemObj.getJSONObject(0);
// item with this pid found
// Edit Text
itemname.setText(item.getString(TAG_item_NAME));
itemdescription.setText(item.getString(TAG_item_description));
} else {
// item with pid not found
}
} 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();
}
}
/*itemname=(TextView)
findViewById(R.id.itemName);
itemdescription=(TextView)
findViewById(R.id.itemdescription);*/
//itemname.setText(name);
//itemdescription.setText(description);
}
activity_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="#bool/fitsSystemWindows">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/status_bar_height"
android:background="?colorPrimary" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/status_bar_height"
android:background="?colorPrimaryDark" />
</LinearLayout>
<FrameLayout
android:id="#+id/flma"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/status_bar_height">
<TextView
android:id="#+id/itemName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:layout_marginTop="80dp"
android:gravity="center"
android:textAllCaps="true"
android:textSize="25dp"
android:textStyle="bold" />
<ImageView
android:id="#+id/itemPhoto"
android:layout_width="fill_parent"
android:layout_height="300dp"
android:layout_gravity="center"
android:background="#000"
android:src="#drawable/header" />
<TextView
android:id="#+id/itemdescription"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="#bool/fitsSystemWindows"
app:headerLayout="#layout/navigation_drawer_header"
app:menu="#menu/navigation_drawer_menu"
app:theme="#style/NavigationViewTheme" />
</android.support.v4.widget.DrawerLayout>
I'm searching and I found that checking if progress dialog is not null set it null the problem can be fix but doesn't work for me.
Does anyone know if I put something wrong in my class?
Thanks!!
SOLUTION:
Thanks to Itzik Samara and ligi for the help and explanation of the problem, I fix the problem removing the lines indicated by Itzik Samara and adding the following code in onPostExecute:
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
try {
itemname.setText(item.getString(TAG_item_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
try {
itemdescription.setText(item.getString(TAG_item_description));
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
You cannot touch UI elements in a background thread ( like setText ) You might want to wrap in runOnUIThread() or do that stuff in onPre / onPost execute ( they are on the UI thread ) and read about android threading
your problem are those 2 lines :
itemname.setText(item.getString(TAG_ITEM_NAME));
itemdescription.setText(item.getString(TAG_ITEM_DESCRIPTION));
2 choices :
send the data to onPostExecute and update the EditText from there
use RunOnUiThread and update the 2 EditTexts inside it
Try adding this in your doInBackground()
runOnUiThread(new Runnable() {
#Override
public void run() {
itemname.setText(item.getString(TAG_item_NAME));
itemdescription.setText(item.getString(TAG_item_description));
}
});
Or put this two lines in onPostExecute()
itemname.setText(item.getString(TAG_item_NAME));
itemdescription.setText(item.getString(TAG_item_description));
Here's your entire Class
public class itemActivity extends AppCompatActivity {
private static final String TAG_SUCCESS = "success";
private static final String TAG_item = "item";
private static final String TAG_item_NAME = "name";
private static final String TAG_item_description = "description";
Integer item_id;
String name;
String username;
String description;
TextView itemname;
TextView itemdescription;
ProgressDialog pDialog;
JSONParser jParser;
RecyclerView recycler;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
Intent i = getIntent();
if (i.hasExtra("item_id")) {
Bundle bd = getIntent().getExtras();
/*if ((!bd.getString("name").equals(null) || bd.getString("name").trim().length() > 0) && (!bd.getString("username").equals(null) || bd.getString("username").trim().length() > 0) && (!bd.getString("description").equals(null) || bd.getString("description").trim().length() > 0)) {
name = bd.getString("name");
username = bd.getString("username");
description = bd.getString("description");
}*/
item_id = bd.getInt("item_id");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setTitle(R.string.app_name);
itemname = (TextView) findViewById(R.id.itemName);
itemdescription = (TextView) findViewById(R.id.itemdescription);
new getitem().execute();
/*recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);*/
}
/**
* Background Async Task to Get complete item details
*/
class getitem extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pDialog != null) {
pDialog = null;
}
pDialog = new ProgressDialog(itemActivity.this);
pDialog.setMessage(getResources().getString(R.string.loadingitem));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Getting item details in background thread
*/
protected String doInBackground(String... params) {
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> myParameters = new ArrayList<NameValuePair>();
myParameters.add(new BasicNameValuePair("item_id", Integer.toString(item_id)));
// getting item details by making HTTP request
// Note that item details url will use GET request
jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(AppConfig.URL_GET_item, "GET", myParameters);
// check your log for json response
Log.d("Single item Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received item details
JSONArray itemObj = json.getJSONArray(TAG_item); // JSON Array
// get first item object from JSON Array
JSONObject item = itemObj.getJSONObject(0);
// item with this pid found
// Edit Text
runOnUiThread(new Runnable() {
#Override
public void run() {
itemname.setText(item.getString(TAG_item_NAME));
itemdescription.setText(item.getString(TAG_item_description));
}
});
} else {
// item with pid not found
}
} 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();
}
}
}

How to filter database output? (android PHP)

I am building an mobile app in where a user logs in and it outputs the contents of my database table which is named "announcements".
What I'm trying to do is to filter out these output based on the "department" column from the "accounts" table in which the users are stored.
The "announcements" table has the column named "receiver".
The contents will only show if the "department" column of the user logged in has the same value as the "receiver column" of the "announcements" column or if the value of the receiver is "all".
How do I do this?
My PHP script
<?php
$host="localhost"; //replace with database hostname
$username="root"; //replace with database username
$password=""; //replace with database password
$db_name="sunshinedb"; //replace with database name
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from announcement";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['services'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
Java class
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList<HashMap<String, String>> arraylist;
ProgressDialog mProgressDialog;
JSONParser jsonParser = new JSONParser();
String email;
String[] services;
private String url = "http://10.0.3.2/sunshine-ems/services.php";
String user_id;
// ALL JSON node names
private static final String TAG_TRANS_ID = "announcement_id";
private static final String TAG_DATE = "date";
private static final String TAG_SERVICES = "title";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_layout);
// get listview
ListView lv = getListView();
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
Single_List.class);
String transaction_id = ((TextView) view
.findViewById(R.id.transac_id)).getText().toString();
i.putExtra("announcement_id", transaction_id);
startActivity(i);
}
});
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(VideosActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading Services");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONObject json = JSONfunctions.getJSONfromURL(url);
// Check your log cat for JSON reponse
Log.d("Service history ", json.toString());
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Locate the array name
jsonarray = json.getJSONArray("services");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
String transac_id = json.getString(TAG_TRANS_ID);
String date = json.getString(TAG_DATE);
String service = json.getString(TAG_SERVICES);
// Retrive JSON Objects
map.put(TAG_SERVICES, service);
map.put(TAG_DATE, date);
map.put(TAG_TRANS_ID, transac_id);
// 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(String file_url) {
mProgressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
VideosActivity.this, arraylist,
R.layout.listview_services, new String[] {
TAG_TRANS_ID, TAG_SERVICES, TAG_DATE },
new int[] { R.id.transac_id, R.id.txt_service,
R.id.txt_date });
// updating listview
setListAdapter(adapter);
}
});
}
}
You are not making any filtering anywhere in your code...
The steps to do it should be these ones (in this order) :
Android side : Calling your webservice (PHP code) with the user's department (in GET or POST parameter)
WS side : Requesting your database with something like SELECT * FROM announcement WHERE receiver = '<department'> OR receiver = 'ALL' where department is the user's department
WS side : Construct the JSON response
Android side : Process the JSON response to display results
The advantages of making it like this :
Limit the number of data transfered (limit network consumption on the Android device and you limit the load on your PHP server)
Limit the number of data processed Android side (limit the load of the Android app : it's not a desktop app ! Never forgive it !)
PS : reading your post and your comment, I really think you should look into these points before starting to make your app : SQL request, PHP MySQL access (as pointed out by #Jay Blanchard), Web services and HTTP protocol, Android AsyncTask

How do I make separators for a ListView with a SimpleAdapter

I'm new to the java programming language and I'm trying to build an app. The app has to make a list of worked hours that have been saved in an MySQL database. I found an example app, that helped me retrieving the data from the database and putting it in a ListView.
But now we get to my problem. I want to put separators in the listview.
Now, the date of the worked hours is in every item of the ListView. I want the date only above the first item.
I've searched the internet for a way to do this, but it didn't help me.
This it the code that gets the data and puts it in a ListView:
public class AllUrenActivity extends ListActivity {
String url_all_uren;
String ip;
String proid;
String uid = MainScreenActivity.uid;
String datum;
String datum1;
ImageView btntoevoegen;
// Progress Dialog
private ProgressDialog pDialog;
TextView tvDatum;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>>urenList;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_UREN = "uren";
private static final String TAG_TRID = "trid";
private static final String TAG_PROID = "proid";
private static final String TAG_WERKZAAMHEID = "werkzaamheid";
private static final String TAG_TIJD = "tijd";
private static final String TAG_DATUM = "datum";
// products JSONArray
JSONArray uren = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_uren);
SharedPreferences settings = getSharedPreferences("databaseIP", 0);
ip = settings.getString("ip", "").toString();
url_all_uren = ("http://"+ip+"/android_connect/get_all_uren.php");
// Hashmap for ListView
urenList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllUren().execute();
// Get listview
ListView lv = getListView();
// on selecting 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 proid = ((TextView) view.findViewById(R.id.tvProid)).getText()
.toString();
String werkzaamheid = ((TextView) view.findViewById(R.id.tvWerkzaamheid)).getText()
.toString();
String trid = ((TextView) view.findViewById(R.id.tvTrid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
AllProjectsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PROID, proid);
in.putExtra(TAG_TRID, trid);
in.putExtra(TAG_WERKZAAMHEID, werkzaamheid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// 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 LoadAllUren extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllUrenActivity.this);
pDialog.setMessage("Uren laden...");
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>();
params.add(new BasicNameValuePair("uid", uid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_uren, "GET", params);
// Check your log cat for JSON reponse
Log.d("Uren: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
uren = json.getJSONArray(TAG_UREN);
// looping through All Products
for (int i = 0; i < uren.length(); i++) {
JSONObject c = uren.getJSONObject(i);
// Storing each json item in variable
String trid = c.getString(TAG_TRID);
String proid = c.getString(TAG_PROID);
String werkzaamheid = c.getString(TAG_WERKZAAMHEID);
String datum = c.getString(TAG_DATUM);
String tijd = c.getString(TAG_TIJD);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TRID, trid);
map.put(TAG_WERKZAAMHEID, werkzaamheid);
map.put(TAG_PROID, proid);
map.put(TAG_TIJD, tijd);
map.put(TAG_DATUM, datum);
// adding HashList to ArrayList
urenList.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 products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllUrenActivity.this, urenList,
R.layout.list_uren, new String[] { TAG_TRID, TAG_PROID, TAG_WERKZAAMHEID, TAG_TIJD, TAG_DATUM},
new int[] { R.id.tvTrid, R.id.tvProid, R.id.tvWerkzaamheid, R.id.tvTijd, R.id.tvDatum });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
list_uren.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvDatum"
android:layout_width="269dp"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="6dip"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="17sp"
android:visibility="visible" />
<ImageView
android:id="#+id/toevoegen"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#android:drawable/ic_menu_add" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvTijd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:text="8:00-12:00"
android:textSize="17sp"
android:textStyle="bold"
android:visibility="visible" />
<TextView
android:id="#+id/tvProid"
android:layout_width="138dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:paddingLeft="6dip"
android:text="Project"
android:textSize="17sp" />
</LinearLayout>
<TextView
android:id="#+id/tvWerkzaamheid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:paddingTop="6dip"
android:text="Werkzaamheid"
android:textSize="17sp" />
</LinearLayout>
all_uren.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
What is the best way to get the date separators? Thank you.
Add this at the end of list_uren.xml before closing the LinearLayout
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#666666" />
You can change the background to whatever you want.

android json add hyperlink to text

Here is my json output sample:
{"podcast":[{"link":"rtsp:\\live.xxx.ro:554\vod\_definst_\mp4:05\rfm_00.mp4","name":"Recording 1"}
For parsing the json code i use this:
private static final String TAG_LINK = "link";
private static final String TAG_NAME = "name";
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
products = json.getJSONArray(TAG_PRODUCTS);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String link = c.getString(TAG_LINK);
String name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_LINK, link);
map.put(TAG_NAME, name);
productsList.add(map);
}
} else {
}
} 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(
PodCast.this, productsList,
R.layout.list_item, new String[] {
TAG_NAME, TAG_LINK },
new int[] { R.id.link, R.id.name });
setListAdapter(adapter);
}
});
For the layout this is the code of the link view:
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:autoLink="web"
android:textColor="#fff"
android:textColorLink="#fff"
android:textStyle="bold"/>
All works well...but in the link view i get the whole link rtsp://live.xxx.ro...etc and i would like to be something like this: NAME So i would have the name and when i click it to open the specified link. Can you guys please help me figure it out how?
Simple...
String href = String.format(" %s ", map.get(TAG_LINK), map.get(TAG_NAME));
textV.setText(Html.fromHTML(href))
Or if you have a link as a resource string; just make sure that the reserved HTML characters aren't converted to HTML entities.
An example that would parse incorrectly:
<string name="a_link"><a href="http://www.google.com">click here</a></string>
To fix it, edit strings.xml manually and convert HTML entities to characters they represent,
so that the above becomes:
<string name="a_link">click here</string>
And it should work.
You need to set a function setOnItemClickListener() and inside it declare something like this:
Uri uri = Uri.parse( "http://www.google.com" );
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );

create spinner options from json data / array

1. My question: How do I take my JSON data and parse it into an array that I can use in my spinner.
Below is my json data:
[["Mike Test 1"],["Mike Test 2"],["hello world"],["TEST MIKE 4"],["TEST MIKE 6"],["aliens,crazy stuff"],["Alien"],["american flags,flags"]]
My script calls a function that gets the data. I know that is working because I have toasted the return value. It should then loop through and assign the values to a new array that is used in the spinner.
Below is my java:
Spinner areaspinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JSONArray jsonArray;
try {
//SETTINGS AND METHOD THAT GETS THE DATA
String spinnerContentType = "styles";
String spinnerURL = "getStyles.php";
String spinner_data = DataCall.getJSON(spinnerURL,spinnerContentType);
//NEW JSONArray OBJECT
jsonArray = new JSONArray(spinner_data);
final String[] array_spinner = new String[jsonArray.length()];
int show_total = jsonArray.length();
//CHECK HOW MANY ITEMS ARE RETURNED
Toast.makeText(flash_tattoo.this, show_total + "test", Toast.LENGTH_LONG).show();
for (int i=0; i<jsonArray.length(); i++)
{
//LOOP AND ASSIGN TO ARRAY
String styleValue = jsonArray.getJSONArray(0).getString(i);
array_spinner[i] = styleValue;
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,array_spinner);
adapter.setDropDownViewResource(R.layout.spinner_layout);
areaspinner.setAdapter(adapter);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is my spinner layout:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textColor="#e70909"
/>
To me it looks like areaspinner is null.
To add a spinner you have something like this in your main.xml.
<Spinner android:id="#+id/mySpinner"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:prompt="#string/mySpinnerText" />
Then in onCreate()
Spinner sp = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, array_spinner);
adapter.setDropDownViewResource(R.layout.spinner_layout);
sp.setAdapter(adapter);

Categories

Resources