how to add data in list view from background class - java

I am getting this exception
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Below is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page2);
lv = (ListView) findViewById(R.id.list_view);
btnNew = (Button)findViewById(R.id.btnAddNew);
btnNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent moveToNewUser = new Intent(getApplication(),ExecutiveInfo2.class);
moveToNewUser.putExtra("ClickType","1");
startActivity(moveToNewUser);
}
});
new Connection2().execute();
// Listview Data
}
private class Connection2 extends AsyncTask {
#Override
protected Object doInBackground(Object... arg0) {
test2();
return null;
}
#Override
protected void onPostExecute(Object s) {
super.onPostExecute(s);
}
}
public void test2() {
HttpURLConnection connection = null;
try {
sharedpreferences = getSharedPreferences("MyPrefs", this.MODE_PRIVATE);
String storedUUID = sharedpreferences.getString("UUID", "");
String url2= "http://crm.xqicai.com/sales/getExecutiveInfo?UUID="+storedUUID;
//String url = "http://crm.xqicai.com/sales/login";
URL postUrl = new URL(url2);
connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编�,�则中文乱�
while (true) {
String str = reader.readLine();
if (str == null) {
break;
}
System.out.println(str);
JSONObject mainObject = new JSONObject(str);
Status = mainObject.getString("status");
int j=0;
if(Status.equals("0"))
{
JSONObject uniObject = mainObject.getJSONObject("data");
JSONArray a = uniObject.getJSONArray("data");
for (int i = 0; i < a.length(); i++) {
JSONObject json_obj = a.getJSONObject(i);
String demo = json_obj.getString("realName");
fetchedNames[j]= demo;
j++;
}
// Adding items to listview
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
}
else
{
JSONObject mainObject2 = new JSONObject(str);
errorMsg = mainObject2.getString("msg");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT).show();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
I'm only a beginner, so please forgive me for asking possibly a stupid question.

What line is giving the error? The problem is that you update a view created in the main thread, in your AsyncTask (a different thread). You should update this view in the onPostExecute of your AsyncTask (this is done in your main thread). I don't see immediately where you update the view.
EDIT:
Your problem should be solved if you put these two lines
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
below this line:
lv = (ListView) findViewById(R.id.list_view);
or in the:
protected void onPostExecute(Object s)

Test that:
ListView lv...
lv.post(new Runnable() {
#Override
public void run() {
//Update UI;
lv.setAdapter(...);
}
})

you can try use Handler with sendEmptyMessage() inside asynctask to pass by exception.
ex.
Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message inputMessage) {
// Adding items to listview
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
}
});
note for code bellow:
//call mHandler.sendEmpyMessage() in asynctask:
if(Status.equals("0"))
{
JSONObject uniObject = mainObject.getJSONObject("data");
JSONArray a = uniObject.getJSONArray("data");
for (int i = 0; i < a.length(); i++) {
JSONObject json_obj = a.getJSONObject(i);
String demo = json_obj.getString("realName");
fetchedNames[j]= demo;
j++;
}
// Adding items to listview
mHandler.sendEmpyMessage(0); //0 or any number is identify code from you want use to check with every action

Related

Cards will not populate with movie names from TMDB API

I am creating an app for a project where you can swipe through movie names and images, for now I am just trying to get the names working but my cards will not populate with the movie names. I had some trouble with the array adapter but I think it's working now and in the correct place. I am using a library from github for the cards and it's worked for other programs just can't get it work with this. Maybe it's because of the model class? just lost when there is no real errors. Item.xml is the design of the card with it's text and background and activity_main.xml is where I reference the library. hellotext is the textview in item.xml. Any help is appreicated!
public class MainActivity extends AppCompatActivity {
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
movieList.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
Api (same class)
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
// model.setId(jsonObject1.getString("vote_average"));
model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList = new ArrayList<>();
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Update***
I fixed the null problem BUT my cards now populate with my project name so I just see one card with com.project300.populateswipecards... any help?
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename = "";
Context context;
SwipeFlingAdapterView flingContainer;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
// Log.d("LIST", "removed object!");
// movieList.remove(0);
// arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
movieList = new ArrayList<>();
// model.setId(jsonObject1.getString("vote_average"));
// model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
At the end of your onPostExecute() method, I see this:
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
I think you're assuming that this will update the list of cards, since earlier in onCreate() you have written this:
flingContainer.setAdapter(arrayAdapter);
However, that is not how the new keyword and Java object references work. These two adapters are completely separate, and flingContainer doesn't "see" the adapter you create in your task.
The easiest way to solve this is likely to re-set the adapter after you create it.
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
Now the problem seems to be this for loop:
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList = new ArrayList<>();
// ...
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
You need to move the ArrayList creation and adapter logic outside of the loop.
movieList = new ArrayList<>();
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList.add(model);
}
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);

Need help to retrieve all the data to listview

I'm trying to make an android application that can read data from a database. but when I try to display some rows in the listview, only the bottom row of the code that I make is displayed.
this is my code for MainActivity
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
getJSON("http://192.168.137.234/librenms/getdata.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) !=null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] alerts = new String[jsonArray.length()];
this is the part to showing the atribute on listview
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
alerts[i] = object.getString("Rule ID");
alerts[i] = object.getString("Device ID");
alerts[i] = object.getString("Time logged");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, alerts);
listView.setAdapter(arrayAdapter);
}
}

JSON ListView filter not working

So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class
Here is my code:
public class jobcategories extends Activity{
private TextView jobData;
private ProgressDialog myprocessingdialog;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobcategories);
myprocessingdialog = new ProgressDialog(this);
jobList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
sv = (SearchView) findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
new JSONTask().execute("https://apidata.com");
}
public class JSONTask extends AsyncTask<String,String, String>{
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialogue
myprocessingdialog.setTitle("Please Wait..");
myprocessingdialog.setMessage("Loading");
myprocessingdialog.setCancelable(false);
myprocessingdialog.setIndeterminate(false);
myprocessingdialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentObject = new JSONArray(finalJson);
for (int i=0; i < parentObject.length(); i++) {
JSONObject job = parentObject.getJSONObject(i);
String JobTitle = job.getString("title");
String JobLocation = job.getString("location");
String finalTitle = JobTitle + " in " + JobLocation;
String JobCompany = "advert by "+job.getString("company");
String JobDescription = job.getString("description");
String JobApply = "How to Apply: " + job.getString("apply");
HashMap<String, String> jobs = new HashMap<>();
jobs.put("title", finalTitle);
jobs.put("company", JobCompany);
jobs.put("description", JobDescription);
jobs.put("apply", JobApply);
jobList.add(jobs);
}
}catch (MalformedURLException e){
Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
myprocessingdialog.cancel();
ListAdapter adapter = new SimpleAdapter(
jobcategories.this, jobList,
R.layout.list_item, new String[]{"title", "company", "description", "apply"},
new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});
lv.setAdapter(adapter);
}
}
}
Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.
Create an interface called OnJsonResultListener like so:
public interface OnJsonResultListener {
void onResult(String result);
}
Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there. Then make the AsyncTask take a OnJsonResultListener in the constructor. Then in the onPostExecute method, call listener.onResult(results);
This is a simple way of making a callback.

Getting and Parsing JSON in the same Activity (Null Pointer Exception)

I want to get and parse json in the same activity but when I try to do this I get
Null Pointer Exception
I think I am getting this error because background task is slower than my code.
In My main activity:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new BackgroundTask().execute();
categoryAdapter = new CategoryAdapter(this,R.layout.row_layout);//I am sure,there is no problem in Category Adapter
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(categoryAdapter);
String id,kategori;
try {
Log.d("jsonstring",JSON_STRING); //I am getting error here JSON_STRING causes null pointer.
jsonObject = new JSONObject(JSON_STRING);
int count = 0;
jsonArray = jsonObject.getJSONArray("server_response");
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("id");
kategori = JO.getString("kategori");
Categories categories = new Categories(id,kategori);
categoryAdapter.add(categories);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Categories contact = (Categories) listView.getItemAtPosition(position);
// Log.d("position",""+position);
// Log.d("id",""+id);
Log.d("id",contact.getId());
Log.d("kategori",contact.getKategori());
}
});
Background Task class:
class BackgroundTask extends AsyncTask<Void,Void,String> {
String json_url= "exampleurl"; // I am sure, here is correct!
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((json_string = bufferedReader.readLine())!=null){
stringBuilder.append(json_string+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public BackgroundTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TextView textView = (TextView)findViewById(R.id.textView);
// textView.setText(result);
JSON_STRING = result;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I have Categories class with id and kategori attributes.
Finally How can I solve this problem? In fact I can parse after getting JSON.

Show JSON Array in ListView - Combine

I know this question keeps popping up but my code is slightly different from the other ones, so I don't know where I need to make my changes.
I want to put data ("fest_name") into an ArrayList ("festivals") and make it appear in a ListView.
This is my code for JSON:
public void getFestivals() {
Thread thread_getdata = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
String link = "http://pou-pou.de/stagedriver/android/uebersicht.php";
HttpPost httppost = new HttpPost(link);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
final ArrayList<String> festivals = new ArrayList<String>();
Log.i("Response", "Response : " + response);
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobj = jsonarray.getJSONObject(i);
final String fest_name = jsonobj.getString("fest_name");
festivals.add(fest_name);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread_getdata.start();
}
And this is for the ListView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fahrt_anbieten1);
ListView lvFestivals = (ListView) findViewById(R.id.lvFestivals);
getFestivals();
ListAdapter festivalsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, festivals);
lvFestivals.setAdapter(festivalsAdapter);
}
I just don't know how to combine the two ones: if I run the app, I just get an empty page, but no real errors.
I would be so happy if anyone could help!
First, using Thread to make network requests isn't recommended.
Second, Apache HTTP has some extra code around simple network requests. When you could instead use Volley (you'll need compile 'com.android.volley:volley:1.0.0')
If you implement the below code, you should get something like this listview.
public class FestListActivity extends AppCompatActivity
implements Response.Listener<JSONArray>, Response.ErrorListener {
private ListView mListView;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(android.R.layout.list_content);
mListView = (ListView) findViewById(android.R.id.list);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
mListView.setAdapter(mAdapter);
getFestivals();
}
private void getFestivals() {
String festURL = "http://pou-pou.de/stagedriver/android/uebersicht.php";
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest req = new JsonArrayRequest(festURL, this, this);
queue.add(req);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
}
#Override
public void onResponse(JSONArray response) {
mAdapter.clear();
try {
for (int i = 0; i < response.length(); i++) {
final JSONObject festObj = response.getJSONObject(i);
int festId = Integer.valueOf(festObj.getString("id_fest"));
String festName = festObj.getString("fest_name");
mAdapter.add(festId + " - " + festName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
After the adapter is not a problem if you put the loop
public void getFestivals() {
Thread thread_getdata = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
String link = "http://pou-pou.de/stagedriver/android/uebersicht.php";
HttpPost httppost = new HttpPost(link);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
final ArrayList<String> festivals = new ArrayList<String>();
Log.i("Response", "Response : " + response);
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobj = jsonarray.getJSONObject(i);
final String fest_name = jsonobj.getString("fest_name");
festivals.add(fest_name);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
ListAdapter festivalsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, festivals);
lvFestivals.setAdapter(festivalsAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread_getdata.start();
}
Put it on the ListView variable OnCreate
ListView lvFestivals;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fahrt_anbieten1);
lvFestivals = (ListView) findViewById(R.id.lvFestivals);
getFestivals();
}

Categories

Resources