this is my code for getting data from a PHP site into a ListView.
package be.pressd.arrangementen;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
Button fetch;
EditText et;
String aantalPersonen;
private ListView lv;
private ArrayAdapter<String> listAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fetch = (Button) findViewById(R.id.fetchButton);
et = (EditText) findViewById(R.id.aantalPersonen);
// Find the ListView resource.
lv = (ListView) findViewById(R.id.arrangementenLijst);
listAdapter = new ArrayAdapter<String>(this, R.layout.line_row);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), "Click nummer " + position, Toast.LENGTH_LONG).show();
String arrangement = (String) lv.getItemAtPosition(position);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), ArrangementItem.class);
// sending data to new activity
i.putExtra("arrangement", arrangement);
startActivity(i);
}
});
fetch.setOnClickListener(this);
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://mywebsite/thephpform.php?aantpers=" + aantalPersonen;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try
{
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
try
{ listAdapter.clear();
JSONArray Jarray = new JSONArray(result);
for(int i=0; i < Jarray.length(); i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
String name = Jasonobject.getString("naam");
listAdapter.add(name);
}
this.progressDialog.dismiss();
lv.setAdapter( listAdapter);
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fetchButton :
aantalPersonen = et.getText().toString();
if (aantalPersonen.trim().equals("")) {
Toast.makeText(this, "Gelieve het aantal personen in te geven", Toast.LENGTH_SHORT).show();
return;
}
else
{
new task().execute();
break;
}
}
}
}
It is my first Android code ever, so besides my question it is possible that this code can be made better.
What I would like to do is to show ALL data, nicely, which was gotten from the website. But, as a ListView can not contain the ID and other data, I'm wondering if I can reuse the data in the JSONObject to be shown in next screen (on click of ListView item) ?
Greetings and thanks in advance,
Davy
Create variables for which you want to store information and loop through JsonArray and get each JsonObject and parse/extract information that you need and store it in variables.
here is sample code to iterate JsonArray //Here response is JsonArray
Create Simple class like
public class PersonInfo{
String name,address; //Create variables of your requirement.
//Add Getter Setter Methods for these variables
}
//End of class PersonInfo
ArrayList<PersonInfo> persons = new ArrayList<PersonInfo>();
PersonInfo person;
JSONObject product;
try
{
for (int j = 0; j < response.length(); j++)
{
person = new Person();
product = response.getJSONObject(j);
person.name = product.getString("JSON_KEY_NAME"); //like these assign values to each variable of PersonInfo class
//Other values initialization
}
persons.add(person); // Add PersonInfo object to ArrayList
}
catch (Exception e)
{
e.printStackTrace();
}
something like that .
you can get json values upon your requirments.
This is just sample code .
You could
save the JSON and parse it again later (you would have to do a lot of parsing)
save the data you parse from the json
in sharedpreferences (only if small amount of data)
in a local sqlite db (probably cleanest approach with best user experience, but a lot of work since you have to create a class that does all the db CRUD operations)
It depends on your data. For user preferences I would use SharedPreferences, for larger amounts a local DB. Also you could create some objects to store the data you need, maybe as signletons or something, and parse the stored JSONs everytime you start the app.
See the google docs on data storage for reference.
To save data you are getting in background task you have to use shared preferences.
Refer this link to get details about shared preferences.
To pass data to next page you have to use following code :
Intent intent = new Intent( currentActivity.this, NextActivity.class);
intent.putExtra("key", "value");
startActivity(intent);
On nextActivity.java add following code inside onCreate()
Intent currentPageIntent = getIntent();
String strValue = currentPageIntent.getStringExtra("key");
If you are having any other data type than string you have to use other method instead of getStringExtra()
To get id of item clicked, you can use following code :
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
if (i == id) {
//Add your code here
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally { }
}
});
Note that you have to process jsonData on your own. This is just sample code I used in one of my porjects.
Related
im new here, sorry if i doing something idiot question,
for the Issues
i already create an app like that below, and all the value in the spinner obtained by JSON in this link
and this happens when the application running,
Spinner
but i want to set if someone choose "ardie halim" the 2nd spinner just show "mobile developer", and if someone choose "indah" the 2nd spinner showing "database oracle", and so on
i tried to find the tutorial from go*gle, but i dunno what the right keyword to find out,
FYI about my code MainActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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;
public class MainActivity extends AppCompatActivity {
ArrayList<String> listItems=new ArrayList<>();
ArrayAdapter<String> adapter;
Spinner sp;
ArrayList<String> listItems2=new ArrayList<>();
ArrayAdapter<String> adapter2;
Spinner sp2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=(Spinner)findViewById(R.id.spinner);
sp2=(Spinner)findViewById(R.id.spinner2);
adapter= new ArrayAdapter<>(this, R.layout.spinner_layout, R.id.txt, listItems);
adapter2= new ArrayAdapter<>(this, R.layout.spinner_layout, R.id.txt, listItems2);
sp.setAdapter(adapter);
sp2.setAdapter(adapter2);
}
public void onStart(){
super.onStart();
BackTask bt=new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
ArrayList<String> list2;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
list2=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://zxccvvv.netne.net/dosen.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;
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);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("nama_dosen"));
list2.add(jsonObject.getString("mat_kul"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
listItems2.addAll(list2);
adapter.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
}
}
}
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
if(list.get(position).equals("ardie halim")){
listItems2.clear();
listItems2.add("mobile developer");
adapter2.notifyDataSetChanged();
}
else if(list.get(position).equals("indah")){
listItems2.clear();
listItems2.add("database oracle");
adapter2.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
The Below Code is For Set Json Data to Spinner
try {
Gson gson = new Gson();
String json = gson.toJson(response.body());
JSONObject jsonObject = new JSONObject(json);
Log.d("check", "jsonData : " + json);
List<String> allGoverNames = new ArrayList<String>();
allGoverNames.add(0, "Select Governorate");
JSONArray cast = jsonObject.getJSONArray("governorate");
for (int i = 0; i < cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
governorateNamenameString = actor.getString("governorate_name");
allGoverNames.add(governorateNamenameString);
}
GoverdataAdapter = new ArrayAdapter<String>
(context, android.R.layout.simple_spinner_item, allGoverNames);
GoverdataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
GovernorateSpinner.setAdapter(GoverdataAdapter);
} catch (JSONException e)
{
e.printStackTrace();
}
Like title says, my variable is not updated on AsyncTask onPostExecute()
Here is the code
public class Search extends AppCompatActivity {
ArrayList<paire> Sectors = new ArrayList<paire>();//paire is my proper class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Rechercher rech = new Rechercher();
rech.execute();
//PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF 0
/*
*
*
BLA BLA BLA BLA
*
*
*/
}
public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{
#Override
protected ArrayList<paire>doInBackground(String... strings) {
/*
*
Process of creating the arrayList myArray
*
*/
onPostExecute(myArray);//I put this desesperatly xD it doesn't change anything
return myArray;
}
protected void onPostExecute(ArrayList<paire>myArray) {
for (int u = 0; u < myArray.size(); u ++){
paire r = myArray.get(u);
Sectors.add(r);
}
//PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF myArray
}
}
}
Well myArray is created from data gotten from dataBase (HTTP connection, JSON result ...) and the result is a very acceptable JSON output; there's no problem here, it's just that Sectors is not updated if I try to use it on Main.
I don't know if I really understand the onPostExecute; or there's a problem !
Thank you
onPostExcecute will call automatically just return your array in doBackground and pass ArrayList instead of void in AsyncTask<String, Void, ArrayList<paire>> and change return type of doInBackground to ArrayList<paire>
try this:
public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{
#Override
protected ArrayList<paire> doInBackground(String... strings) {
/*
*
Process of creating the arrayList myArray
*
*/
//onPostExecute(myArray); // remove this line no need to add . this will call automatically.
return myArray;
}
protected void onPostExecute(ArrayList<paire> myArray) {
for (int u = 0; u < s.size(); u ++){
Sectors.set(u, s.get(u));
}
//PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF myArray
}
}
hope this help.
Is this building without errors? I dont believe that you can call onPostExecute from doInBackground and I dont see anywhere in the code where there is a variable called "s" but s.size() is what is controlling the number of times the for loop iterates. So in the current code, Sectors.set would never be called.
you should read careful about asyncTask again.
Modify you asynTask as below
public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{
#Override
protected Void doInBackground(String... strings) {
/*
*
Process of creating the arrayList myArray
*
*/
/* don't need to call this function, asynctask will call it automatically
onPostExecute(myArray);
*/
return myArray;
}
protected void onPostExecute(ArrayList<paire>myArray) {
if (Selector.size() > 0) {
Selector.clear();
}
for (int u = 0; u < s.size(); u ++){
Sectors.add(s.get(u));
}
//PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF myArray
}
}
package caci.elmouchir;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import android.util.Log;
import android.widget.*;
import android.widget.Spinner;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
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.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Search extends AppCompatActivity {
private void setSectors(String[] lesSec){
Spinner sec = (Spinner) findViewById(R.id.spinnerSecteur);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lesSec);
sec.setAdapter(adapter);
sec.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
ArrayList<paire> Sectors = new ArrayList<paire>();
ArrayList<paire> Branchs = new ArrayList<paire>();
ArrayList<paire> SBranchs = new ArrayList<paire>();
ArrayList<paire> Activities = new ArrayList<paire>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
String Code = "X.XX.XX.XXX";
Rechercher rech = new Rechercher();
rech.execute();
Log.e("log_tag", Integer.toString(Sectors.size()));
//Log.e("log_tag", Integer.toString(Sectors.size()));
Button search = (Button)findViewById(R.id.buttonSearch);
search.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
EditText motcle = (EditText)findViewById(R.id.editMotCle);
if (motcle.getText().toString().isEmpty())
motcle.setError("Entrez un mot clé");
}
});
/*
*
*
*
*
C O N N E X I O N A L A B A S E D E D O N N E E S
*
*
*
*
*/
}
public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{
#Override
protected ArrayList<paire> doInBackground(String... strings) {
String result = "";
ArrayList<paire> s = new ArrayList<paire>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.145/test/getActivities.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
//convert response to string
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//Log.e("log_tag", result);
try{
JSONArray jArray = new JSONArray(result);
ArrayList<paire> b = new ArrayList<paire>();
ArrayList<paire> sous = new ArrayList<paire>();
ArrayList<paire> a = new ArrayList<paire>();
for(int i=0;i<jArray.length();i++){
JSONObject json_data = (JSONObject)jArray.getJSONObject(i);
if (json_data.getString("friendly_url").toString().length() == 2){
paire p = new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString());
s.add(p);
}
else if(json_data.getString("friendly_url").toString().length() == 3){
b.add(new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
}
else if(json_data.getString("friendly_url").toString().length() == 4){
sous.add(new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
}
else{
a.add(new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
}}
//Log.e("log_tag", Integer.toString(s.size()));
// onPostExecute(s, b, sous, a);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
return s;
}
protected void onPostExecute(ArrayList<paire>s) {
/*Sectors = s;
Branchs = b;
SBranchs = sous;
Activities = a;*/
for (int u = 0; u < s.size(); u ++){
paire r = s.get(u);
Sectors.add(r);
}
Log.e("log_tag", "loool: "+Integer.toString(Sectors.size()));
}
}
public class paire{
String title;
String url;
paire(String p, String u){
this.title = p;
this.url = u;
}
String getTitle(){
return this.title;
}
String getUrl(){
return this.url;
}
}
}
I'm New to android development and I don't understand clearly how to create a appwidget for application that parse JSON Data and display in list.
I solved my problem using this link (https://laaptu.wordpress.com/2013/07/19/android-app-widget-with-listview/).
It has Series of Tutorials
(1.app widget with listview
2.populate app widget listview with data from web
3.download images and show on imageview of appwidget with listview
4.setting update interval on appwidget with listview
5.how to make appwidget update work after phone reboot)
To Use Simple JSON URL to fetch images and texts, i made the following changes in RemoteFetchService.java from third tutorial,
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.mk.widgets.data.DatabaseManager;
import com.example.mk.widgets.data.FileManager;
public class RemoteFetchService extends Service {
private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
JSONObject jsonobject;
JSONArray jsonarray;
AQuery aquery;
private String remoteJsonUrl = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors";
public static ArrayList<ListItem> listItemList;
private int count = 0;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
/*
* Retrieve appwidget id from intent it is needed to update widget later
* initialize our AQuery class
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
appWidgetId = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
aquery = new AQuery(getBaseContext());
new DownloadJSON().execute();
return super.onStartCommand(intent, flags, startId);
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Create an array
listItemList = new ArrayList<ListItem>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(remoteJsonUrl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("actors");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
ListItem listItem = new ListItem();
listItem.heading = jsonobject.getString("name");
listItem.content = jsonobject.getString("country");
listItem.imageUrl = jsonobject.getString("image");
listItemList.add(listItem);
}
storeListItem();
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
}
/**
* Instead of using static ArrayList as we have used before,no we rely upon
* data stored on database so saving the fetched json file content into
* database and at same time downloading the image from web as well
*/
private void storeListItem() {
DatabaseManager dbManager = DatabaseManager.INSTANCE;
dbManager.init(getBaseContext());
dbManager.storeListItems(appWidgetId, listItemList);
int length = listItemList.size();
for (int i = 0; i < length; i++) {
ListItem listItem = listItemList.get(i);
final int index = i;
aquery.ajax(listItem.imageUrl, Bitmap.class,new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap bitmap, AjaxStatus status) {
super.callback(url, bitmap, status);
storeBitmap(index, bitmap);
};
});
}
}
/**
* Saving the downloaded images into file and after all the download of
* images be complete begin to populate widget as done previously
*/
private void storeBitmap(int index, Bitmap bitmap) {
FileManager.INSTANCE.storeBitmap(appWidgetId, bitmap,
listItemList.get(index).heading, getBaseContext());
count++;
Log.i("count",String.valueOf(count) + "::"+ Integer.toString(listItemList.size()));
if (count == listItemList.size()) {
count = 0;
populateWidget();
}
}
/**
* Method which sends broadcast to WidgetProvider so that widget is notified
* to do necessary action and here action == WidgetProvider.DATA_FETCHED
*/
private void populateWidget() {
Intent widgetUpdateIntent = new Intent();
widgetUpdateIntent.setAction(WidgetProvider.DATA_FETCHED);
widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
appWidgetId);
sendBroadcast(widgetUpdateIntent);
this.stopSelf();
}
}
JSONfunctions.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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 JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Hope this helps someone and Great thanks to ( https://stackoverflow.com/users/739306/laaptu ) for the tutorials.
I am new to android. I got stuck on this point. I just want to get data of listview onclick event to another page by position. here is my code.
I got project contains error in the following line
i.putExtra("testonAray",listContents[position].toString());
Entire code below:
package com.example.listviewdemo;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.listviewdemo.CustomHttpClient;
public class MainActivity extends ListActivity {
TextView txt;
String returnString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String name="sandeep";
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("email",
name.toString()));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://indiaontaxi.com/android/myaccount.php", // your ip address if using localhost server
//"http://omega.uta.edu/~kmr2464/jsonscript.php", // in case of a remote server
postParameters);
// store the result returned by PHP script that runs MySQL query
String result = response.toString();
//parse json data
try {
JSONArray jArray = new JSONArray(result);
int jArrayLength = jArray.length();
final ArrayList<String> listContents = new ArrayList<String>(jArrayLength);
for(int i =0; i<jArray.length(); i++){
JSONObject json_data = jArray.getJSONObject(i);
listContents.add(json_data.getString("source"));
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContents));
txt = (TextView) findViewById(R.id.txt);
//myListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ));
}catch(JSONException e){
Log.e("log_tag","Error parsin data "+e.toString());
}
}
catch (Exception e) {
Log.e("log_tag","Error in http connection!!" + e.toString());
}
/* setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
txt = (TextView) findViewById(R.id.txt);
*/
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
// txt.setText(items[position]);
// Try to send the items[position] in the intent
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("testonAray",listContents[position].toString());
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
// Try this code
i.putExtra("testonAray",listContents[position].toString());
// Replace the line
i.putExtra("testonAray",listContents.get(position).toString());
In Android 3.0 and above you need to do all network based actions separate from the UI thread.That is in a Async class. HEre is a similar post I made a few days ago; have a look at how you can make Async calls to JSON that are in a URL Trouble with JSON exception - Android
Change the code
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("testonAray",listContents[position].toString());
to
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("testonAray",listContents[position].toString());
I am trying since yesterday to make my application take some JSON data generated by a PHP file and then display this data in a list view.
The PHP File is encoding data using encode method:
echo json_encode($results);
Viewed from the browsers view source the JSON generated by file.php looks like this:
["","CSD1939","CSD1939"]
The JSONLint (A great tool) validates this as a correct JSON format.
When I am trying to use my application to fetch this JSON from the webservice I am fetching it as a String first but I am having trouble passing it to the adapter and making it display correctly.
I only managed until now to create a listview that displays a String Array.
What is the best way to fetch this JSON data and display it in the list.
package com.example.ams;
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;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ViewClasses extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_classes);
new GetInfo().execute();
// ==============Functionality Start====================
// final ListView listview = (ListView) findViewById(R.id.listview);
}
private class GetInfo extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
// Fetch the JSON from the web and we pass it as a string to
// the ON POST EXECUTE method
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"file.php?get=XXX");
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(this.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
protected void onPostExecute(String result) {
// Here it should turn it into a JSON and then display it in a list.
// Gets the list view
final ListView listview = (ListView) findViewById(R.id.listview);
// Converts the String to a JSON array
System.out.println(result);
JSONArray jsonArray;
try {
System.out.println(result);
jsonArray = new JSONArray(result);
Log.i(ViewClasses.class.getName(), "Number of entries "
+ jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(ViewClasses.class.getName(),
jsonObject.getString("text"));
// Converts JSON array to Java Array
final ArrayList<String> list = new ArrayList<String>();
// values instead of jsonArray
if (jsonArray != null) {
int len = jsonArray.length();
for (int i1 = 0; i1 < len; i1++) {
list.add(jsonArray.get(i).toString());
}
}
final StableArrayAdapter adapter = new StableArrayAdapter(
getApplicationContext(),
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
}
My Layout XML file looks like this
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Running this code I am getting a blank screen.
Any help, pointers, hints would be greatly appreciated
It is just returning JSONArray with Strings, so you should not create JSONObject from it.
JSONObject jsonObject = jsonArray.getJSONObject(i);
this will cause Exception as JSONArray doesn't contain JSONObjects.
So parse like this
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}