Vertical Progress Bar on Android - android

I want to implement progress bar on list view for data that am getting from Mysql server here is my code any new suggestion are welcome for an example change your layout or anything which will make implementation easy as am neophyte
public class teststatusActivity extends BaseActivity {
String myJSON = "" ;
private static final String TAG_RESULTS = "result";
private static final String TAG_TICKET = "ticket_id";
private static final String TAG_Status = "ticket_status";
private static final String TAG_Status1 = "ticket_status1";
private static final String TAG_Status2 = "ticket_status2";
private static final String TAG_Status3 = "ticket_status3";
private static final String TAG_I = "";
public static final String DATA_URL = "http://103.3.62.23/complain_dashboard/api/getTicketStatus.php?ticket_id=";
public String ticketID;
JSONArray peoples = null;
ListView list;
ArrayList<HashMap<String, String>> usersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teststatus);
list = (ListView) findViewById(R.id.listView);
usersList = new ArrayList<HashMap<String, String>>();
getData();
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONObject pe = jsonObj.getJSONObject(TAG_RESULTS);
String id = pe.getString("ticket_id");
String status = pe.getString("ticket_status");
String stat = null;
String stat1 = null;
String stat2 = null;
String stat3 = null;
if (pe.get("ticket_status").equals("0")) {
stat = "Feedback Sent To Team";
}
if (pe.get("ticket_status").equals("1")) {
stat1 = "Technical Team is Working on it";
}
if (pe.get("ticket_status").equals("2")) {
stat2 = "Your Report is About To Resolve";
}
if (pe.get("ticket_status").equals("3")) {
stat3 = "Resolved";
}
HashMap<String, String> users = new HashMap<String, String>();
users.put( TAG_TICKET , id );
users.put(TAG_Status, stat );
users.put(TAG_Status1, stat1 );
users.put(TAG_Status2, stat2);
users.put(TAG_Status3, stat3);
usersList.add(users);
ListAdapter adapter = new SimpleAdapter(
teststatusActivity.this, usersList, R.layout.list_item,
new String[]{TAG_TICKET, TAG_Status,TAG_Status1, TAG_Status2, TAG_Status3 },
new int[]{R.id.feed, R.id.feedS, R.id.feedwork, R.id.abouttoresolve, R.id.resolved}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
SharedPreferences sharedPref = getSharedPreferences("tcktid", Context.MODE_WORLD_READABLE);
final String ticket =sharedPref.getString("tid", null);
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(DATA_URL + ticket);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
} ;

Related

How to use Fragment in Android?

iam using menu slidding, this code for call other class
}else if (id == R.id.list) {
//Set the fragment initially
StockProduct fragment = new StockProduct();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
but fragment error i don't know why...
and this is my class code
public class StockProduct extends Fragment implements ListView.OnItemClickListener {
String myJSON;
private static final String TAG_RESULTS = "result";
private static final String TAG_NAME = "name_product";
private static final String TAG_ID = "product_id";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.list_product, container, false);
list = (ListView) view.findViewById(R.id.allproduct);
personList = new ArrayList<HashMap<String, String>>();
getData();
return view;
}
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(Config.ALLPRODUCT_URL);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
}
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID, id);
persons.put(TAG_NAME, name);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
StockProduct.this.getActivity(), personList, R.layout.list_product_component,
new String[]{TAG_ID,TAG_NAME},
new int[]{R.id.idproduct, R.id.nameproduct}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this.getActivity(), StockProductView.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String product_id = map.get(TAG_ID).toString();
intent.putExtra(Config.TAG_PRODUCT_ID,product_id);
startActivity(intent);
}}
and this is log error
Try replacing this line,
StockProduct fragment = new StockProduct();
with
Fragment fragment = new StockProduct();
Make sure all your import statements import support fragment

Android Development - Parsing JSON

I'm trying to get the values from my mySql database and display them in a listView. However when I click the button to display them I get the following error message : org.json.JSONException: No value for establishments.
I know that the TAG_RESULTS is empty but I don't know what I'm supposed to put in to it.
Here is my code
public class SecondPage extends AppCompatActivity {
String myJSON;
//There is no value for this TAG_RESULTS ON LINE 116
private static final String TAG_RESULTS="establishments";
private static final String TAG_NAME = "name";
private static final String TAG_PICTURE = "picture";
JSONArray establishments_JSON = null;
ArrayList<HashMap<String, String>> establishmentsList;
//JSONArray establishments = null;
//Array establishments = null;
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_location_listview);
listView = (ListView) findViewById(R.id.listView);
establishmentsList = new ArrayList<HashMap<String,String>>();
getData();
}
public void getData(){
//changed the middle parameter to a string from a void
class GetDataJSON extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
Log.d("GETTING JSON DATA", "HERE....");
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://10.102.11.109/findandeat_xampp_data/get_all_establishments.php");
//String loginDetails = ServerConnection.RUSH_SERVER_ADDRESS + "login.php?userName=" + userNameInput + "&password=" + passwordInput;
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
Log.d("STARTING INPUT STREAM", "HERE....");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
result = sb.toString();
} catch (Exception e) {
// Oops
Log.d("CATCH ANY ERRORS", "HERE....");
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
Log.d("myjson",myJSON);
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
Log.d("myjson",myJSON);
JSONObject jsonObj = new JSONObject(myJSON);
establishments_JSON = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<establishments_JSON.length();i++){
JSONObject c = establishments_JSON.getJSONObject(i);
String pizzeriaName = c.getString(TAG_NAME);
String pizzeriaPicture = c.getString(TAG_PICTURE);
String chineseName = c.getString(TAG_NAME);
String chinesePicture = c.getString(TAG_PICTURE);
String cafeName = c.getString(TAG_NAME);
String cafePicture = c.getString(TAG_PICTURE);
String indianName = c.getString(TAG_NAME);
String indianPicture = c.getString(TAG_PICTURE);
String ChipShopName = c.getString(TAG_NAME);
String ChipShopPicture = c.getString(TAG_PICTURE);
//Error im getting is that there is no value for the result
//with the JSON
HashMap<String,String> establishment_items = new HashMap<String,String>();
establishment_items.put(TAG_NAME,pizzeriaName);
establishment_items.put(TAG_PICTURE,pizzeriaPicture);
establishment_items.put(TAG_NAME,chineseName);
establishment_items.put(TAG_PICTURE,chinesePicture);
establishment_items.put(TAG_NAME,cafeName);
establishment_items.put(TAG_PICTURE,cafePicture);
establishment_items.put(TAG_NAME,indianName);
establishment_items.put(TAG_PICTURE,indianPicture);
establishment_items.put(TAG_NAME,ChipShopName);
establishment_items.put(TAG_PICTURE,ChipShopPicture);
establishmentsList.add(establishment_items);
}
ListAdapter adapter = new SimpleAdapter(
SecondPage.this, establishmentsList, R.layout.activity_current_location_items,
new String[]{TAG_NAME,TAG_PICTURE},
new int[]{R.id.establishment_name, R.id.establishment_picture}
);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
XMLdatabase column names
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
column name in database
The other types of restuarants have the same naming system applied
It will generate this error because there is the parameter you want. So you can validate:
//if exists
if(jsonObj.has(TAG_RESULTS)){
}
The same should do to verify certain parameters exist or not in the JSON object, so you save trouble with exceptions.
use .has(String) and isNull(String)
.has(String) checks if the JSONObject contains a specific key
.isNull(String) checks if the value associated with the key is null or if there is no value
So , your code will be
if (jsonObj.has(TAG_RESULTS) && !jsonObj.isNull(TAG_RESULTS)) {
establishments_JSON = jsonObj.getJSONArray(TAG_RESULTS);
}
I hope to be helpful for you .

How to refresh listview items once list items are updated - to be used in onResume

I have an update fragment using which i will update data in my database. Once the update is done i move back to 'view the data from database' fragment and i need the list to be updated. I think i have to write code for this inside onResume() but i don't know how to do it.
Code for 'view the data from database' fragment:
public class Testing extends Fragment {
String uname="921312104053";
private static final String TAG_RESULTS="result";
private static final String TAG_Sname = "Subject_name";
private static final String TAG_Scode = "Subject_code";
private static final String TAG_Sgrade ="Grade";
ListView lv;
JSONArray subjects = null;
String myJSON;
ListAdapter adapter;
ArrayList<HashMap<String, String>> subList,subList1;
public Testing() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_testing,
container, false);
disp(view);
return view;
}
public void disp(View view)
{
lv = (ListView)view.findViewById(R.id.list);
subList = new ArrayList<HashMap<String,String>>();
getData(view);
}
public void getData(View view){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://10.0.2.2/markolepsy/android_connect/testing.php?usrname="+uname);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
subjects = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<subjects.length();i++){
JSONObject c = subjects.getJSONObject(i);
String sname = c.getString(TAG_Sname);
String scode = c.getString(TAG_Scode);
String sgrade = c.getString(TAG_Sgrade);
HashMap<String,String> records = new HashMap<String,String>();
records.put(TAG_Sname,sname);
records.put(TAG_Scode,scode);
records.put(TAG_Sgrade,sgrade);
subList.add(records);
}
adapter = new SimpleAdapter(
getActivity(), subList, R.layout.list_layout,
new String[]{TAG_Sname,TAG_Scode,TAG_Sgrade},
new int[]{R.id.subject_name, R.id.subject_code, R.id.grade}
);
lv.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Using notifyDataSetChanged() may suite your needs.
Refer to this: How to refresh Android listview?
Edit:
adapter = new SimpleAdapter(
getActivity(), subList, R.layout.list_layout,
new String[]{TAG_Sname,TAG_Scode,TAG_Sgrade},
new int[]{R.id.subject_name, R.id.subject_code, R.id.grade}
);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
The above code should help.

How to update listview when ever data is updated?

I am new in android, i want to update my list view when ever data is inserted in mysql database.I have searched in internet and i have used adapter.notifyDataSetChanged(); but i keep getting the error "The method notifyDataSetChanged() is undefined for the type ListAdapter"
Code:
public class Messages extends BaseActivity{
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_RESULTS="result";
private static final String TAG_USERNAME = "username";
private static final String TAG_NAME = "message_recd";
private static final String TAG_ADD ="message_sent";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
TextView textView = (TextView) findViewById(R.id.fname);
textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
editTextName = (EditText) findViewById(R.id.editTextName);
b=(Button)findViewById(R.id.button1);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etname=(EditText)findViewById(R.id.editTextName);
if( etname.getText().toString().trim().equals("")){
etname.setError( "Cannot be left empty!" );
}
// TODO Auto-generated method stub
else{
Intent intent = getIntent();
String fName = intent.getStringExtra("fname");
String message = etname.getText().toString();
insertToDatabase(message, fName);
}
etname.setText("");
}
});
}
//send messages start
private void insertToDatabase(String message, String fName1){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String fname = params[1];
//InputStream is = null;
String message = editTextName.getText().toString();
Intent intent1 = getIntent();
String fName = intent1.getStringExtra("fname");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("message", message));
nameValuePairs.add(new BasicNameValuePair("username", fName));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/test/test.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
//is = entity.getContent();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(message, fName1);
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
if(c.has("message_recd"))
name = c.getString("message_recd");
else
address = c.getString("message_sent");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
/*ListAdapter adapter = new SimpleAdapter(
Messages.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);*/
ListAdapter adapter = new SimpleAdapter(
Messages.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);
// http://www.vogella.com/tutorials/AndroidListView/article.html
// http://stackoverflow.com/questions/8166497/custom-adapter-for-list-view
list.setAdapter(adapter);
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://10.0.2.2/progress_card/messages/get_messages.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}
The notifyDataSetChanged method is defined and implemented in BaseAdapter, the supertype of SimpleAdapter. So just add a cast to BaseAdapter or SimpleAdapter.
when you perfrom any add() or remove() operation to your personlist,
call adpater.notifyDataSetChanged(); method to Update ListView
Refernce : notifyDataSetChanged example

Show data in listview with Asynctask

I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
And this JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject AmbilJson(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;
}
}
Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
private class myProses extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);
}
protected Void doInBackground(Void... params) {
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
protected void onPostExecute(Void unused) {
adapter_listview();
dialog.dismiss();
}
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?
Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Kies Facebook-account");
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {
private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
contests_listView = (ListView) findViewById(R.id.activity_listView);
pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
listActivities = new ArrayList<Object>();
new FetchActivitesTask().execute();
}
public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {
int i =0;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "Your URL Here";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse.getJSONArray(nodes);
for (i = 0; i < jsonnodes.length(); i++)
{
String str = Integer.toString(i);
Log.i("Value of i",str);
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode.getJSONObject(node);
bean = new ActivitiesBean();
bean.title = jsonnodevalue.getString(title);
bean.image = jsonnodevalue.getString(field_activity_image_fid);
listActivities.add(bean);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
displayAdapter();
}
}
public void displayAdapter()
{
adapter = new ActivityAdapter(this, listActivities);
contests_listView.setAdapter(adapter);
contests_listView.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// your onclick Activity
}
});
}
}
util.class
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
return iStream_to_String(instream);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
ActivityBean.java
public class ActivitiesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}

Categories

Resources