ChooseCategory.java
public class ChooseCategory extends ListActivity {
private ListView lv;
//ArrayAdapter<FoodStores> arrayAdapter;
private ArrayList<FoodStores> storefoodList;
private String URL_STORES = "http://10.0.2.2/get_stores.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = (ListView)findViewById(R.id.list);
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
}
private class GetFoodStores extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
String json = jsonParserFood.makeServiceCall(URL_STORES, ServiceHandlerFood.GET);
Log.e("Response: ", " > " + json);
if(json != null){
try{
JSONObject jsonObj = new JSONObject(json);
if(jsonObj != null){
JSONArray storeListFood = jsonObj.getJSONArray("storelistfood");
for(int i = 0; i < storeListFood.length(); i++){
JSONObject storeFoodObj = (JSONObject) storeListFood.get(i);
FoodStores foodStores = new FoodStores(storeFoodObj.getInt("id"),storeFoodObj.getString("STORENAME"));
storefoodList.add(foodStores);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Log.e("JSON Data", "No data received from server");
}
return null;
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
populateListView();
}
}
Here is the function of my populateListView
private void populateListView(){
List<String> labels = new ArrayList<String>();
for(int i = 0; i < storefoodList.size(); i++){
labels.add(storefoodList.get(i).getName());
}
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.restaurant_list,labels);
Log.d("Labels:", labels.toString());
lv.setAdapter(listAdapter);
}
What I am trying to do here is to get the list of stores from PHP to Android via JSON and store them in ArrayList and then populate them into ListView. I have tried displaying labels, it is displaying the correct stuff.
The error from Emulator is that it just shows blank screen and then it crashes.
The error from logcat is
java.lang.NullPointerException
at call.rocket.user.callarocket.ChooseCategory.populateListView
Do like
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.restaurant_list,labels);
setListAdapter(listAdapter);
as you directly extends ListActivity also remove
lv = (ListView)findViewById(R.id.list);
and make sure your ListView id is android:id="#android:id/list"
Go to Tutorial
Related
I want to do a listview ,and I have lot of data want to insert it.
so I want to use doinbackground.
but when I use doinbackground,my listview never appera anymore,
how can I do ?
this is my code:
public class Listening extends AppCompatActivity {
ArrayList<Listenlist> listenlists = new ArrayList<Listenlist>();
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listening);
listview = (ListView) findViewById(R.id.list);
}
public void seraechsql2(){
String result = dblisten.executeQuery();
try{
JSONArray jsonArray = new JSONArray(result);
for(int i =0; i < jsonArray.length(); i++)
{
JSONObject jsonData = jsonArray.getJSONObject(i);
track=jsonData.getString("track");
Listenlist team = new Listenlist("T"+track+".mp3");
listenlists.add(team);
final ListenlistAdapter adapter = new ListenlistAdapter(this, R.layout.listenlist, listenlists);
listview.setAdapter(adapter);
}
}
catch(Exception e){}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
seraechsql2();// it can not show listview...
return null;
}
protected void onProgressUpdate(String... progress) {}
#Override
protected void onPostExecute(String unused) {}
}
}
thanks.
You shouldn't update UI in doInBackground because it's background thread. It should be update in onPostExecute. Try this code:
public class Listening extends AppCompatActivity {
ArrayList<Listenlist> listenlists = new ArrayList<Listenlist>();
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listening);
listview = (ListView) findViewById(R.id.list);
}
public void seraechsql2(){
String result = dblisten.executeQuery();
try{
JSONArray jsonArray = new JSONArray(result);
for(int i =0; i < jsonArray.length(); i++)
{
JSONObject jsonData = jsonArray.getJSONObject(i);
track=jsonData.getString("track");
Listenlist team = new Listenlist("T"+track+".mp3");
listenlists.add(team);
}
}
catch(Exception e){}
}
class DownloadFileAsync extends AsyncTask<String, String, ArrayList<Listenlist>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
seraechsql2();
return listenlists;
}
protected void onProgressUpdate(String... progress) {}
#Override
protected void onPostExecute(ArrayList<Listenlist> result) {
final ListenlistAdapter adapter = new ListenlistAdapter(this, R.layout.listenlist, result);
listview.setAdapter(adapter);
}
}
}
for(int i =0; i < jsonArray.length(); i++)
{
// each time you create a new adapter and set it !!!
Listenlist team = new Listenlist("T"+track+".mp3");
listenlists.add(team);
final ListenlistAdapter adapter = new ListenlistAdapter(this, R.layout.listenlist, listenlists);
listview.setAdapter(adapter); // HERE!!!
}
I think you should change like this
public class Listening extends AppCompatActivity {
ArrayList<Listenlist> listenlists = new ArrayList<Listenlist>();
ListView listview;
final ListenlistAdapter adapter = new ListenlistAdapter(this, R.layout.listenlist, listenlists); // initilize adapter
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listening);
listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter); // only set once
}
public void seraechsql2(){
String result = dblisten.executeQuery();
try{
JSONArray jsonArray = new JSONArray(result);
for(int i =0; i < jsonArray.length(); i++)
{
JSONObject jsonData = jsonArray.getJSONObject(i);
track=jsonData.getString("track");
Listenlist team = new Listenlist("T"+track+".mp3");
listenlists.add(team);
}
adapter.notifyDataSetChanged();// notify listview that data has changed!
}
catch(Exception e){}
}
}
I have the next problem, I tried to send Arraylist<string> values from AsyncTask class to other class call graphics but I don’t know what I do wrong and how to get Arraylist<string> values in the other class, because I have a lot of sintaxis errors I my code
AsyncTask class
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//v funcional
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected ArrayList<String> doInBackground(Void... voids) {
String Id ="";
String Time ="";
String Pressure="";
ArrayList<String> IdArray = new ArrayList<String>();
ArrayList<String> TimeArray = new ArrayList<String>();
ArrayList<String> PressureArray = new ArrayList<String>();
String IdS=""+IdArray;
String TimeS=""+TimeArray;
String PresureS=""+PressureArray;
data.set(1,TimeS);
data.set(2,TimeS);
data.set(3,TimeS);
return data;
}
#Override
protected void onPostExecute(ArrayList<String> result){
super.onPostExecute(result);
Graphics.data.setText(data);
}}
The graphics class
public class Graphics extends AppCompatActivity {
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphics);
Button firstButton = (Button) findViewById(R.id.json);
data = (TextView) findViewById(R.id.msgTxt);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetch process = new fetch();
ArrayList<String> data= process.execute();
data.get(1);
}
});
}
you can create an interface which your "Graphics" implements it , and pass it to your AsyncTask class.
like this
public interface BlaBlaBla {
void doBla(ArrayList<String> myBla);
}
and in your "Graphics" :
class Graphics extends AppCompatActivity implements BlaBlaBla {
fetch process = new fetch(this);
}
and for asyncClass :
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//constructor
BlaBlaBla bla;
public fetch(BlaBlaBla bla){
this.bla=bla;
}
//when your task is complete use bla.doBla(pass your array here);
}
my solution
Fetch class
public class Fetch extends AsyncTask<Void,Void,String[][]> {
public static int KEY = 0;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected String[][] doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http:xxxxxxx/xxx.json";
String jsonStr = sh.makeServiceCall(url);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
int nTiempos=jsonObj.length();
String[] IdKeyArray = new String[nTie];
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(String.valueOf(i));
IdKeyArray[i] = c.getString("Key");
String[][] valores={IdKeyArray};
return valores;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
And this is the "call" the other class where I get the values
private String[][] valores;
Fetch process = new Fetch();
process.execute();
try {
valores=process.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
pm.setText(String.valueOf(valores[Fetch.Key][0]));
}
}
}
I am working on an android application. In this application, I have to retrieve data from a web service and put it in a listview, but it is not retrieving anything. I don't know what I am doing wrong here. Maybe someone can help me with this.
Webservice: http://10.247.240.53/kas/lampen.php
Mainactivity:
`
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listview);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
getData();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Showdata.class);
intent.putExtra("teeltbed", listView.getItemAtPosition(position).toString());
startActivity(intent);
}
});
}
private void getData()
{
String getData = null;
String dbResult = "empty";
dbConnect database = new dbConnect(this);
try{
String query = "SELECT * FROM Lamp";
getData = "?query=" + URLEncoder.encode(query, "UTF-8");
String link = "http://10.247.240.53/kas/lampen.php";
dbResult = database.execute(link).get();
}
catch (Exception e){
}
try{
JSONArray ja = new JSONArray(dbResult);
JSONObject jo = null;
data = new String[ja.length()];
for (int i = 0; i < ja.length(); i++)
{
jo = ja.getJSONObject(i);
data[i] = jo.getString("teeltbed");
}
adapter = new ArrayAdapter<String>(this, R.layout.layout_list, R.id.list_item, data);
listView.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}`
im writing an app which needs to get some json from my DB, i receive the data, but now im trying to also view a icon beside the information which is shown in a listview.
The line which is making trouble is:
mChart.setTag(URL);
new DownloadImagesTask.execute(mChart); <------
MainActivity:
public class MainActivity extends Activity {
ListView list;
TextView icon;
TextView name;
TextView developer;
TextView size;
Button Btngetdata;
ArrayList<HashMap<String, String>> mList = new ArrayList<HashMap<String, String>>();
private static String url = "http://appwhittle.com/getdata.php";
private static final String TAG_ITEM = "app_item";
private static final String TAG_ICON = "app_icon";
private static final String TAG_NAME = "app_name";
private static final String TAG_DEVELOPER = "app_developer";
private static final String TAG_SIZE = "app_size";
JSONArray mJsonArray = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
icon = (TextView)findViewById(R.id.icon);
name = (TextView)findViewById(R.id.name);
size = (TextView)findViewById(R.id.size);
developer = (TextView)findViewById(R.id.developer);
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 {
mJsonArray = json.getJSONArray(TAG_ITEM);
for(int i = 0; i < mJsonArray.length(); i++){
JSONObject c = mJsonArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
String developer = c.getString(TAG_DEVELOPER);
String icon = c.getString(TAG_ICON);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ICON, icon);
map.put(TAG_NAME, name);
map.put(TAG_DEVELOPER, "Developer: " + developer);
map.put(TAG_SIZE, size + " MB");
mList.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, mList,
R.layout.list_v,
new String[] {TAG_NAME, TAG_DEVELOPER, TAG_SIZE }, new int[] {
R.id.name, R.id.developer, R.id.size});
ImageView mChart = (ImageView) findViewById(R.id.icon);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImagesTask.execute(mChart);
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 "+ mList.get(+position).get(TAG_NAME), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
DownloadImagesTask:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
return null;
}
}
Any help is much appreciated! Thanks in advance!
Replace
new DownloadImagesTask.execute(mChart);
with
new DownloadImagesTask().execute(mChart);
Try this. It will work.
You need to change
new DownloadImagesTask.execute(mChart);
to
new DownloadImagesTask().execute(mChart);.
Check after changing, hopefully it works fine. Happy coding :)
Change:
new DownloadImagesTask.execute(mChart);
to:
new DownloadImagesTask(mChart).execute();
You have not initialized the object of your DownloadImagesTask by calling constructor.
new DownloadImagesTask().execute(mChart); use like this. Call default constructor by putting ().
//Suppose you have a class "DataFetcher" which extends "AsyncTask<Void,Void,Void>{}"
//to execute this class write the code as follows
new DataFetcher().execute(); //done
I parsed json to adapt for my autocompleteTextView. I tried to match the value parsed by my json object with the value entered by user.
But some where i am failing. please help me in matching these values.
i have to match the string(acity) that is entered by user with my parsed json value stored in responseList.
This is how i am trying.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
final List<String> responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
So lets assume you need to match a certain city before you intent to a map :
private final List<String> responseList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
for(int i=0; i<responseList.size(); i++) {
if(responseList.get(i).equals(aCity)) {
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
}
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
It should be something like that if I didnt guess your intent wrongly.