I have a listview now i need to pass the listview data to a another activity how do i do it ?
MainActivity
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import java.util.List;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private static String url = "http://216.185.116.35/LOGISTIC/WebServices/json/getDeliveriItems_bak.ashx?id=485";
private static final String TAG_OS = "android";
private static final String TAG_VER = "BagNumber";
private static final String TAG_NAME = "COD";
private static final String TAG_API = "OrderNo";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java
package learn2crack.listview.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
json = sb.toString();
json = "{ \"android\":"+json+"}";
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
I have found some explanation how to pass data but I am having problem at new AdapterView.OnItemClickListener()
The problem is
oslist.get(+position)
should be
oslist.get(position)
Also you have
private static final String TAG_NAME = "COD"; // key for name is COD
map.put(TAG_NAME, name);
then
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = oslist.get(position).get("COD");
Intent intent = new Intent(ActivityName.this, YOURACTIVITY.class);
intent.putExtra("key", name);
startActivity(intent);
}
});
Should move setAdapter coe out of for loop
Also change to
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
pDialog.dismiss();
try {
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter)
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = oslist.get(position).get("COD");
String ver = oslist.get(position).get(TAG_VER);
String api = oslist.get(position).get(TAG_API);
Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
intent.putExtra("key", name);
intent.putExtra("key1", ver);
intent.putExtra("key2", api);
startActivity(intent);
}
});
}
In Another Activtiy
String name =getIntent().getStringExtra("key");
String api =getIntent().getStringExtra("key1");
String ver =getIntent().getStringExtra("key"2);
You should create a custom adapter. Also create a DataModel which will hold all the 3 values (Version, Name and Api). Make it Serializable.
public class MyModel implements Serializable{
private static final long serialVersionUID = 1L;
String version, name, api;
public MyModel(String modelVer, String modelName, String modelApi){
version = modelVer;
name = modelName ;
api = modelApi;
}
//Add Getters and Setters
}
Instead of creating HashMap<String, String> map = new HashMap<String, String>(); Create
ArrayList<MyModel> modelList = new ArrayList<MyModel>();
then in OnItemClickListener()
//To send data
MyModel modelToPass = modelList.get(position);
intent.putExtra("MyObject", modelToPass);
//To get data
getIntent().getSerializableExtra("MyObject");
for example you can pass the position of item that is clicked by below code
public void onListItemClick(ListView parent, View v, int position,
long id){
Intent intent = new Intent(getApplicationContext(), YourActivity.class);
intent.putExtra("pos", position);
startActivity(intent);
}
in YourActivity oncreate() method
Intent current=getIntent();
int position=current.getExtras().getInt("pos");
for sending your data you can make class below
public class Information implements Serializable {
public String BagNumber;
public String COD;
public String OrderNo;
public String SubOrderNo;
......
......
}
and for send it
Information details = new Information ();
details.BagNumber = "";
details.COD = "12";
details.OrderNo = "ff";
....
....
Intent i = new Intent(getApplicationContext(), YourActivity.class);
i.putExtra("inf", details);
startActivity(i);
For receive it
Information model = (Information ) getIntent().getSerializableExtra("inf");
Related
I want to Delete a record from the database when i click on the Buttton.
The Button i set in the listView.
I want to perfrom this on ListView Here i tried following way but its not working..
Here My API
<?php
include("connection.php");
$tbl = "abc";
$idToDelete = $_GET["id"];
$delete_row = mysql_query("DELETE FROM $tbl WHERE o_id=".$idToDelete);
$response["delete"] = array();
$response["success"]=1;
// push single product into final response array
echo json_encode($response);
?>
ListviewAdapter.java
package com.example.sachin.alertbox;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ActionMenuView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button add;
Spinner spinner;
ListView listview;
LinearLayout linearlayout;
JSONObject jsonobject;
private static String url_addevent = "http ://10.0.2.2/portal/order_product.php";
public static String url_visitor= "http://10.0.2.2/portal/fetchorder_of_user.php";
JSONParser jParser = new JSONParser();
JSONArray ownerObj;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> delivery_fetch = new ArrayList<String>();
ListViewAdapterorder listadapter;
EditText qty;
LinearLayout layout;
ActionMenuView.LayoutParams params;
LinearLayout mainLayout;
PopupWindow popUp;
final Context context = this;
ArrayAdapter<String> adapter;
Button Delete;
ArrayList<String> listItems = new ArrayList<>();
String stringqty,stringspinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.clickme);
popUp = new PopupWindow(this);
layout = new LinearLayout(this);
mainLayout = new LinearLayout(this);
listview = (ListView)findViewById(R.id.listview);
Delete=(Button)findViewById(R.id.delete);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
spinner=(Spinner)promptsView.findViewById(R.id.spinner);
adapter = new ArrayAdapter<String>(getApplication(), R.layout.spinner_layout, R.id.txt, listItems);
spinner.setAdapter(adapter);
spinner.setSelection(0);
qty=(EditText)promptsView.findViewById(R.id.qty);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
stringqty=qty.getText().toString();
stringspinner=spinner.getSelectedItem().toString();
addvisitor();
new fetchorder().execute();
Toast.makeText(getApplicationContext(), "qty : " + stringqty +stringspinner, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
private void addvisitor() {
service(stringqty,stringspinner);
}
private void service(String qty,String sp) {
class AddVisitclass extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
//#Override
protected void onPreExecute() {
// Create a progressdialog
super.onPreExecute();
//loading = ProgressDialog.show(getApplicationContext(), "Please Wait...!!!", null, true, true);
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> param = new HashMap<String, String>();
param.put("quantity", params[0]);
param.put("model", params[1]);
String result = ruc.sendPostRequest(url_addevent, param);
Log.d("Result", result);
Log.d("Data", param.toString());
return result;
}
//#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//loading.dismiss();
Toast.makeText(getApplicationContext(), "Service Added Successfully...!!!", Toast.LENGTH_LONG).show();
/* Intent i1 = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i1);*/
}
}
AddVisitclass regi = new AddVisitclass();
regi.execute(qty,sp);
}
ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();
private class fetchorder extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}
public void onStart() {
super.onStart();
BackTask bt = new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected void onPreExecute() {
super.onPreExecute();
list = new ArrayList<>();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/portal/spinner.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
list.add("Please Select Model");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("m_model"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
listItems.addAll(list);
}
}
}
Here MainActivity.java ListView class
ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();
private class fetchorder extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}
I tried this way but the delete is not happening.. please suggest me some coede for this.
Try this.
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
datlist.remove(position);
o_aid.remove(position);
o_aproduct.remove(position);
o_aqty.remove(position);
o_atotal.remove(position);
Snackbar.make(view, "Record Delete Succesfully", Snackbar.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
Call me:85110 51548 if any issue
There is issue in your connection.php pls check I have checked but not issue from php queries but if connection.php has issue you will not find because if record is deleted it returns 1 if any problem it returns 0 in your code return 0 it means record is not deleted successfully.
Write The Following Code in Your php and change it into connection.php
/*connection.php */
$host="your host";
$username="your user name";
$password="your password";
$dbname="your database name";
$con = new mysqli($host, $username, $password,$dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
/*code.php */
include('connection.php');
$tbl = "abc";
$idToDelete = $_GET["id"];
$sql="DELETE FROM $tbl WHERE o_id=".$idToDelete;
$delete_row = $con->query($sql);
$response["delete"] = array();
$response["success"]=1;
/// push single product into final response array
echo json_encode($response);
** In short there is a problem in connection file thats why not deleted that record **
I have used a MYSQL Database and connected it to my Android App using PHP. I added a sample row in the table and the PHP Script is returning JSON. I have tried my best in parsing the JSON and displaying it in a list. But it does not seem to be working. Able to run the App - But does not display content - Only shows the Dialog. It seems to work in Case of an Activity - What changes should be made to make it work for a Fragment. Here is my LogCat when I open up the fragment - http://prntscr.com/3f6k0a .
package com.example.socbeta;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class events extends ListFragment {
private ProgressDialog pDialog;
private static final String READ_EVENTS_URL ="http://socapptest.comoj.com/socbeta/events.php";
//JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_EventName = "EventName";
private static final String TAG_POSTS = "posts";
private static final String TAG_ID = "ID";
private static final String TAG_DATE = "Date";
private static final String TAG_MESSAGE = "message";
private JSONArray mEvents = null;
private ArrayList<HashMap<String, String>> mEventList;
public events(){}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.events, container, false);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadEvents().execute();
}
public void updateJSONdata() {
mEventList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_EVENTS_URL);
try {
mEvents = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mEvents.length(); i++) {
JSONObject c = mEvents.getJSONObject(i);
String EventName = c.getString(TAG_EventName);
String content = c.getString(TAG_MESSAGE);
String Date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EventName, EventName);
map.put(TAG_MESSAGE, content);
map.put(TAG_DATE, Date);
mEventList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(getActivity(), mEventList,
R.layout.list_item,
new String[] { TAG_EventName, TAG_MESSAGE,TAG_DATE },
new int[] { R.id.eventname, R.id.message,R.id.date });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
});
}
public class LoadEvents extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Events...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
EDIT :
Got my code to work. The Problem was with the JSON Structure. I did not Navigate properly and this gave me a "No Value for message" Error. For others who might be having same issues - Remember that when you have { in your JSON , you use JSONArray and when you have [ you use JSONObject. You need to navigate module wise through your JSON.
try this code
pass json string to this method . it will work
public JSONObject getJSONfromURL(String url)
{
InputStream is = null;
JSONObject jObj = null;
String json = "";
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget= new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
how is it possible to parse some Json Data from web and put them in a listview.
Inside of them i would like to search something, I'm searching now for a while in the internet but I wasn't successfull.
I still can Parse JSON and pu them in a listview but how can I search?
Here my Code
MainAct.:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "*****";
//JSON Node Names
private static final String TAG_OS = "android";
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
List<list> varr = yourlist;
for (list result : varr) {
// action such as.. if result
}
hope this help
I am working trying to solve an issue on an activity, but I am not able to find the reason for the behaviour.
I have a list view activity (Activity A), if the app user taps on a list row, a second list view activity (Activity B) is shown and all expected list objects are on the list.
Then, if the user navigates from activity B back to activity A, and selects the same or another row, then activity B is shown again, but none object is shown on the list.
I was told by another SO user to include a onResume method. I have done it, but the issue is not solved.
Here you have the activity B code:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class ofertas_list extends ListActivity {
private ProgressDialog pDialog;
// JSON node keys
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idCategoria";
private static final String TAG_CATEGORIAS = "Categorias";
// URL to get contacts JSON
private static String url = "http://xxxxx/android_ofertaslist.php?id=";
// JSON Node names
private static final String TAG_NOMBREEMPRESA = "nombreEmpresa";
private static final String TAG_IDEMPRESA = "idEmpresa";
private static final String TAG_DESCRIPCIONEMPRESA = "descripcionEmpresa";
private static final String TAG_STRIMAGEN = "strImagen";
private static final String TAG_DIRECCIONEMPRESA = "direccionEmpresa";
private static final String TAG_TELEFONOEMPRESA = "telefonoEmpresa";
private static final String TAG_FACEBOOKEMPRESA = "facebookEmpresa";
private static final String TAG_EMAILEMPRESA = "emailEmpresa";
private static final String TAG_TEXTOOFERTA = "textoOferta";
private static final String TAG_HORARIOEMPRESA = "horarioEmpresa";
private static final String TAG_CATEGORIAEMPRESA = "categoriaEmpresa";
private static final String TAG_LATITUDEMPRESA = "latitudEmpresa";
private static final String TAG_LONGITUDEMPRESA = "longitudEmpresa";
private static final String TAG_VALORACIONEMPRESA = "valoracionEmpresa";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onResume(){
super.onResume();
new GetContacts().execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
// getting intent data
Intent in = getIntent();
// JSON node keys
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_ID);
// URL to get contacts JSON
this.url = url+email;
this.setTitle(name);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
//cambiar por los nuevos campos
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
//Starting single contact activity
//cambiar por los nuevos campos
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, cost);
startActivity(in);
}
});
// Calling async task to get json
//new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ofertas_list.this);
pDialog.setMessage("Cargando datos...");
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
contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String nombreEmpresa = c.getString(TAG_NOMBREEMPRESA);
String descripcionEmpresa = c.getString(TAG_DESCRIPCIONEMPRESA);
String strImagen = c.getString(TAG_STRIMAGEN);
String direccionEmpresa = c.getString(TAG_DIRECCIONEMPRESA);
String telefonoEmpresa = c.getString(TAG_TELEFONOEMPRESA);
String facebookEmpresa = c.getString(TAG_FACEBOOKEMPRESA);
String emailEmpresa = c.getString(TAG_EMAILEMPRESA);
String textoOferta = c.getString(TAG_TEXTOOFERTA);
String horarioEmpresa = c.getString(TAG_HORARIOEMPRESA);
String categoriaEmpresa = c.getString(TAG_CATEGORIAEMPRESA);
String valoracionEmpresa = c.getString(TAG_VALORACIONEMPRESA);
String latitudEmpresa = c.getString(TAG_LATITUDEMPRESA);
String longitudEmpresa = c.getString(TAG_LONGITUDEMPRESA);
String idEmpresa = c.getString(TAG_IDEMPRESA);
// Phone node is JSON Object
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_IDEMPRESA, idEmpresa);
contact.put(TAG_NOMBREEMPRESA, nombreEmpresa);
contact.put(TAG_DESCRIPCIONEMPRESA,descripcionEmpresa);
contact.put(TAG_STRIMAGEN,strImagen);
contact.put(TAG_DIRECCIONEMPRESA,direccionEmpresa);
contact.put(TAG_TELEFONOEMPRESA,telefonoEmpresa);
contact.put(TAG_FACEBOOKEMPRESA,facebookEmpresa);
contact.put(TAG_EMAILEMPRESA,emailEmpresa);
contact.put(TAG_TEXTOOFERTA,textoOferta);
contact.put(TAG_HORARIOEMPRESA,horarioEmpresa);
contact.put(TAG_CATEGORIAEMPRESA,categoriaEmpresa);
contact.put(TAG_VALORACIONEMPRESA,valoracionEmpresa);
contact.put(TAG_LATITUDEMPRESA,latitudEmpresa);
contact.put(TAG_LONGITUDEMPRESA,longitudEmpresa);
// adding contact to contact list
contactList.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(
ofertas_list.this, contactList,
R.layout.list_item_ofertas, new String[] { TAG_NOMBREEMPRESA, TAG_DIRECCIONEMPRESA}, new int[] { R.id.name,
R.id.email });
setListAdapter(adapter);
}
}
}
I am trying to solve the issue for two days but still no success. Please you are kindly requested to give me an advice on how to solve the issue.
CODE FOR ACTIVITY A:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class categorias_list extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://XXXX/android_categoriaslist.php";
// JSON Node names
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idCategoria";
private static final String TAG_CATEGORIAS = "Categorias";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
//Starting single contact activity
Intent in = new Intent(getApplicationContext(),
ofertas_list.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, cost);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(categorias_list.this);
pDialog.setMessage("Cargando datos...");
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
contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// Phone node is JSON Object
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
// adding contact to contact list
contactList.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(
categorias_list.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_ID}, new int[] { R.id.name,
R.id.email });
setListAdapter(adapter);
}
}
}
CODE FOR SERVICE HANDLER:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
You have to need maintain arraylist globalaly use
Adapter.notifyDatasetChanged(); for updating the list:
List view can be updated by updating your array adapt
YourArrayAdapterName.notifyDataSetChanged;
Above code must be added in your Activities onResume Method, Which is your firt activity for the List
Example:
#Override
protected void onResume() {
super.onResume();
yourAdapterName.notifyDataSetChanged();
// do other stuffs here.
}
I am new to android. I am implementing a project in which I want to get the data from the back end and display on my android screen.
The Json I am trying to call is:-
[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds#fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin#qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagaraj","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]
My JsonParser.java is as follows:-
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}
}
/* public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Programmer");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
*/
And my activity.java is as follows:-
package com.example.library;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SecondActivity extends Activity
{
private Context context;
private static String url = "http://192.168.0.100:3000/users.json";
private static final String TAG_ID = "id";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_MIDDLE_NAME = "middle_name";
private static final String TAG_LAST_NAME = "last_name";
// private static final String TAG_POINTS = "experiencePoints";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(SecondActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(SecondActivity secondActivity) {
Log.i("1", "Called");
context = secondActivity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context 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[] { TAG_ID, TAG_FIRST_NAME,
TAG_MIDDLE_NAME, TAG_LAST_NAME }, new int[] {
R.id.id, R.id.first_name, R.id.middle_name,
R.id.last_name });
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
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 id = c.getString(TAG_ID);
String first_name = c.getString(TAG_FIRST_NAME);
String middle_name = c.getString(TAG_MIDDLE_NAME);
String last_name = c.getString(TAG_LAST_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_MIDDLE_NAME, middle_name);
map.put(TAG_LAST_NAME, last_name);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
public ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
I am not able to show anything on the emulators for users,whereas I am able to fetch the data from the server
Actually in the project I want to display all the users present in the library.I am accessing the server which is on Ubuntu.
The following message is displayed on the console(Terminal):-
Started GET "/users.json" for 192.168.0.104 at 2013-05-05 22:05:01 -0700
Processing by UsersController#index as JSON
User Load (0.4ms) SELECT "users".* FROM "users" WHERE (users.deleted = 0) ORDER BY users.id DESC
Admin Load (0.3ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 AND (admins.deleted = 0) ORDER BY admins.id DESC LIMIT 1
Completed 200 OK in 4ms (Views: 2.1ms | ActiveRecord: 0.6ms)
[2013-05-05 22:05:01] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
However i am not able to display the data on the android screen/emulator.
Please help me with this.
I missed your setAdapterList()method.
Any error for your json pasers? and can you put your activity which is inherited from SecondActivity?
//modify getListView
public ListView getListView() {
// TODO Auto-generated method stub
listView = (ListView)findViewById(r.your.listview);
return listView;
}
//modify setListAdapter
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
lv.setAdapter(adapter);
}