Having some Trouble with List adapter and its arrguments? - android

ProgressTask.java
public class ProgressTask extends AsyncTask<String, Void, Boolean>{
private ProgressDialog dialog;
private ListActivity activity;
private Context context;
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
private static String url = "http://api.cartperk.com/v1/supportedoperator";
private static final String OPCODE="code";
private static final String OPNAME="name";
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { OPCODE, OPNAME}, new int[] {
R.id.opcode, R.id.opname});
activity.setListAdapter(adapter);
lv = activity.getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++)
{
try {
JSONObject c = json.getJSONObject(i);
String opcode = c.getString(OPCODE);
String opname = c.getString(OPNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(OPCODE,opcode);
map.put(OPNAME,opname);
jsonlist.add(map);
}
catch(JSONException e)
{
e.printStackTrace();
}
}
return null;
}
its showing error in the list_item, R.id.opcode , R.id.opname should i create a new XML file and write the code there or else will generate dynamically my present layout file is as show below can you guys help me out
<RelativeLayout>
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<RealativeLayout>
Not Able to Understand.

should i create a new XML file and write the code there or else will generate dynamicaly my present layout file
Look at the constructor
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
You need to have list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/opcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="49dp"
android:layout_marginTop="51dp"
android:text="TextView" />
<TextView
android:id="#+id/opname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:layout_marginRight="72dp"
android:text="TextView" />
</RelativeLayout>
Edit:
I think you do not have a ListActivity in the first place.
Secondly your json is
[ // is a json array noder
{ // json object node
"operatorCode": "AC",
"operatorName": "Aircel"
},
But you have
private static final String OPCODE="code"; // should be operatorCOde
private static final String OPNAME="name"; // operatorName
Keys are not matching the column names
Thirdly you do not have a json object at the top its a json array.
public class MainActivity extends ListActivity
{
private ProgressDialog dialog;
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
private static String url = "http://api.cartperk.com/v1/supportedoperator";
private static final String OPCODE="operatorCode";
private static final String OPNAME="operatorName";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
dialog = new ProgressDialog(this);
dialog.setMessage("Loading...");
new TheTask().execute();
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet(url);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String res = EntityUtils.toString(resEntity);
JSONArray json = new JSONArray(res);
for(int i=0;i<json.length();i++)
{
JSONObject c = json.getJSONObject(i);
String opcode = c.getString(OPCODE);
String opname = c.getString(OPNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(OPCODE,opcode);
map.put(OPNAME,opname);
jsonlist.add(map);
}
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, jsonlist,
R.layout.list_item, new String[] { OPCODE, OPNAME}, new int[] {
R.id.opcode, R.id.opname});
setListAdapter(adapter);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.show();
}
}
}
Snap

Related

How to return the id of selected item of listview

Hello friends i am new to android and i am learning about android programming. I am working with my friends. I have web service from which i am showing list of cities in listview now my friend give me task that is when i will click on city then id of that city return me so i don't how to do so please anybody can help me to do so.
public class CityNameActivity extends ListActivity{
private TextView displayText;
ListView list;
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
private static final String TAG_ID = "city_id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// 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
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_ID, id);
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} 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);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
final ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}}
cityname_mai_activity.xml
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select City"
android:id="#+id/textView4"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="25dp"/>
city_list_item:
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textSize="16sp"
android:textStyle="bold" />
You have to use the Spinner like these below:
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this,R.layout.spinner_item,ARRAYLIST_DATA_HERE);
aa.setDropDownViewResource(R.layout.spinner_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String items=spinner.getSelectedItem().toString();
Log.i("Selected item : ",items);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
return true;
Use the spinner_item xml
xmlns:android="http://schemas.android.com/apk/res/android"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#BAB7BA"
android:ellipsize="start"
android:gravity="left"
android:padding="10dip"
android:textColor="#color/white" />
Did you check On Click Listener for your ListView ?? I think that will solve your problem.. Use onClikcListener's on ItemClick event which will give you position and based on that position you can get item from your Arraylist which will give you id from that..

checkbox isclicked giving null value

I have a class which extends listactivity. I am parsing data from a json file and putting data in list. i have also created a checkbox to check student is present if it checked. For that i have created an array to get the position from list. I am getting the student names but checkbox is giving me null values. Please Help!!! Here is my code,
public class Student_data extends ListActivity {
private ProgressDialog pDialog;
private Button button;
ListView lv;
// URL to get contacts JSON
private static String url = "http://10.0.2.2/studentdata.json";
private static int[] present, absent;
private static int i = 0, j = 0, x;
// JSON Node names
private static final String TAG_DEP_ID = "dep_id";
private static final String TAG_HEAD = "stdata";
private static final String TAG_NAME = "name";
private static final String TAG_ENROLL = "enrollment";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_list);
studentList = new ArrayList<HashMap<String, String>>();
button = (Button) findViewById(R.id.saveData);
button.setOnClickListener(new ButtonClick());
lv = getListView();
new GetContacts().execute();
lv.setOnItemClickListener(new CheckBoxClick());
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Student_data.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// 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
data = jsonObj.getJSONArray(TAG_HEAD);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String id = c.getString(TAG_DEP_ID);
String name = c.getString(TAG_NAME);
String enrll = c.getString(TAG_ENROLL);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_DEP_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_ENROLL, enrll);
// adding contact to contact list
studentList.add(contact);
}
} 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);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*/
ListAdapter adapter = new SimpleAdapter(Student_data.this, studentList, R.layout.data_item,
new String[] { TAG_NAME }, new int[] { R.id.name });
setListAdapter(adapter);
}
}
public class CheckBoxClick implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
CheckBox chkbox = (CheckBox) arg1;
if (chkbox.isChecked()) {
present[i] = arg2;
i++;
}
if (chkbox.isChecked()) {
absent[j] = arg2;
j++;
}
}
}
public class ButtonClick implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
}
}
data_item.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="horizontal"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:weightSum="2" >
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#000"
android:textSize="16sp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/chkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
Try this
if (((CheckBox) arg1).isChecked()) {
//your code
}

Posting data from listview of android to server in a loop using multipart

I have a list of data displayed in a listview .... data is parsed from JSON and displayed here
Present Snapshot::
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>();
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
TextView name;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.RestaurantNameID);
flag = (ImageView) itemView.findViewById(R.id.flag);
name.setText(resultp.get(MainActivity.NAME));
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
return itemView;
}
}
ListOfContacts.java
public class ListOfContacts extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String FLAG = "flag";
EditText mEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(ListOfContacts.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7004/DescriptionSortedPrice/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(ListOfContacts.NAME, jsonobject.getString("Person_Name"));
map.put(ListOfContacts.FLAG, "http://54.218.73.244:7004/"+jsonobject.getString("Image_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) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<LinearLayout
android:id="#+id/RestaurantPicImageLinearViewID"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/flag"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/RestaurantNameID"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<RelativeLayout
android:id="#+id/RestaurantDataLinearViewID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/RestaurantPicImageLinearViewID" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
<TextView
android:id="#+id/RestaurantNameID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/RestaurantDataLinearViewID"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:gravity="center"
android:text="Name"
android:textStyle="bold" />
</RelativeLayout>
What i am trying to do ::
I want to post the image and the text data shown in the snapshot to the server
My research::
I use the below code to post the data to server when listview is not involved
Code i use for posting data:
public void postImageData() {
try
{
Bitmap bitmapOrg = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://54.218.73.244:7004/Details/");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
reqEntity.addPart("key", bab);
reqEntity.addPart("key1", new StringBody(name.getText().toString()));
}
catch(Exception e){
//Log.v("Exception in Image", ""+e);
reqEntity.addPart("picture", new StringBody(""));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
}catch(Exception e){
e.getStackTrace();
}
}
note:: URl i want to post the data is also http://54.218.73.244:7004/Details/ and key value pair is also same as i have mentioned above in code
My problem::
I am having difficulty in posting data in a loop one after other since listview is involved
How can i resolve this
{Edit}-2
public class ListOfContacts extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String FLAG = "flag";
EditText mEditText;
Button bTn;
ImageView IV;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
bTn=(Button) findViewById(R.id.List_view_button_id);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
bTn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
// DownloadJSON AsyncTask
class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(ListOfContacts.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
postImageData();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7004/DescriptionSortedPrice/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(ListOfContacts.NAME, jsonobject.getString("Person_Name"));
map.put(ListOfContacts.FLAG, "http://54.218.73.244:7004/"+jsonobject.getString("Image_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) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
public void postImageData() {
try
{
Bitmap bitmapOrg = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://54.218.73.244:7004/Details/");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
reqEntity.addPart("key", bab);
reqEntity.addPart("key1", new StringBody(name.getText().toString()));
}
catch(Exception e){
//Log.v("Exception in Image", ""+e);
reqEntity.addPart("picture", new StringBody(""));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
}catch(Exception e){
e.getStackTrace();
}
}
}
I am having difficulty in posting data in a loop one after other since
listview is involved
=> I can't assume and not sure what kind of difficulty you are facing. But I assume you would want to post all the items data to server.
If this is the case, then follow the below steps:
Create a main AsyncTask
Inside background, write a loop and iterate it through all the items and call the postImageData() function for each iteration.
P.S. this is not a standard and good solution for posting large data but you can create a Post data service so it won't prevent user to play with apps while uploading is being executed.

Json image cant load

i am getting "text" form json, but i can't get "images".
public class JsonSampleActivity extends ListActivity {
private Context context;
// url to make request
private static String url = "http://www.bounty4u.com/android/sample_json.txt";
//JSON Node names
private static final String TAG_TITLE = "name";
private static final String TAG_IMAGE = "url";
// contacts JSONArray
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new ProgressTask(JsonSampleActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ListActivity activity;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
}
#Override
protected void onPostExecute(final Boolean success) {
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_TITLE, TAG_IMAGE },
new int[] { R.id.title, R.id.image1 });
setListAdapter(adapter);
}
protected Boolean doInBackground(final String... args) {
JsonParser jParser = new JsonParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vfuel = c.getString(TAG_TITLE);
String vimage = c.getString(TAG_IMAGE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, vfuel);
map.put(TAG_IMAGE,vimage);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
I am getting an error : resolveUri failed on bad bitmap uri: http://www.bounty4u.com/android/images/angie.jpg
so tell me what is problem?

Why does my ListView not update with SimpleAdapter?

I am retrieving JSON data from my server with which I want to update my ListView with. Everything works fine with retrieving the data but after it's finished and it tries to update the list I just get an empty page with no errors. Log.d("ListLocations", "after") is able to run as well so I don't see any problems with PostExecute and intiliasation of SimpleAdapter
I have adapted my code from this tutorial: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/#ff0000
This is my ListActivity class:
public class ListLocations extends ListActivity
{
//Root url and controller
private static String root = "someURL/";
private static String locationsController = "locations";
// Progress Dialog
private ProgressDialog pDialog;
//JSON node names for locations
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_TERRAIN = "terrain";
private static final String TAG_DIFFICULTY = "difficulty";
private static final String TAG_RATINGS = "ratings";
private static final String TAG_UID = "uid";
private static final String TAG_LONG= "long";
private static final String TAG_LAT= "lat";
private static final String TAG_DISTANCE= "distance";
private static final String TAG_COMID= "comid";
//Will be used to contain the list of locations extracted from JSON
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_locations);
new GetLocations().execute(root + locationsController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_list_locations, menu);
return true;
}
class GetLocations extends AsyncTask<String, Void, Void>
{
// private ProgressDialog pDialog;
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(ListLocations.this);
pDialog.setMessage("Loading locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public Void doInBackground(String... urls)
{
try
{
JSONHandler jsonHandler = new JSONHandler();
JSONObject json= jsonHandler.getJSONFromUrl(urls[0]);
Log.d("ListLocations",json.toString());
JSONArray locations = json.getJSONArray("locations");
int length = locations.length();
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < length; i++)
{
JSONObject loc = locations.getJSONObject(i);
//Create HashMap
HashMap<String, String> map = new HashMap<String, String>();
//Get and store values into map
map.put("id", loc.getString(TAG_ID));
map.put("name", loc.getString(TAG_NAME));
map.put("distance", loc.getString(TAG_DISTANCE));
map.put("difficulty", loc.getString(TAG_DIFFICULTY));
map.put("terrain", loc.getString(TAG_TERRAIN));
map.put("ratings", loc.getString(TAG_RATINGS));
map.put("long", loc.getString(TAG_LONG));
map.put("lat", loc.getString(TAG_LAT));
map.put("uid", loc.getString(TAG_UID));
map.put("comid", loc.getString(TAG_COMID));
//Add map to list
list.add(map);
}
System.out.println(list);
}
catch (Exception e)
{
e.printStackTrace();
}
Log.d("ListLocations", "Successfully finished HTTP Request");
return(null);
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Log.d("ListLocations", "inside run");
ListAdapter adapter = new SimpleAdapter(
ListLocations.this, list,
R.layout.list_item, new String[] { TAG_ID,
TAG_NAME},
new int[] { R.id.id, R.id.name });
Log.d("ListLocations", "after");
// updating listview
setListAdapter(adapter);
}
});
}
}
}
This is list_item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- location id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
</LinearLayout>
This is activity_list_locations.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
You never put the data in the list field from the Activity that you use with the SimpleAdapter because the list variable in the doInBackground method is a local variable and not the field. Instead of:
//...
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < length; i++) {
//...
write:
//...
list = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < length; i++) {
//...
so you don't make a local variable and put the elements in the right list.

Categories

Resources