I am working on a small project to help me learn about Android. I made a small ListFragment, but I cannot get it to display anything. I try checking the logs and I don't see any errors.
ListFragment
public class EspnFragment extends ListFragment {
String URL = "url"
DefaultHttpClient defaultClient = new DefaultHttpClient();
JSONObject jsonObject;
EspnAdapter adapter;
EspnObject object = new EspnObject();
private ArrayList<EspnObject> objects = new ArrayList<EspnObject>();
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new EspnAdapter(getActivity(), R.layout.list_item_display);
sendRequest();
adapter.addAll(objects);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
setListShown(true);
}
private void sendRequest() {
new Thread(new Runnable() {
#Override
public void run() {
HttpGet request = new HttpGet(URL);
HttpResponse httpResponse = null;
try {
Log.v("ESPN DATA:", "Getting Data");
httpResponse = defaultClient.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
jsonObject = new JSONObject(json);
JSONArray items = jsonObject.getJSONArray("headlines");
for (int i = 0; i < items.length(); i++) {
JSONObject jsonObj = (JSONObject) items.get(i);
String title = jsonObj.getString("headline");
String date = jsonObj.getString("lastModified");
object.setDate(date);
object.setTitle(title);
objects.add(object);
}
Log.v("ESPN DATA:", "Done");
} catch (Exception e) {
e.getStackTrace();
Log.v("ESPN DATA:", "Caught Error" + e.getMessage());
}
}
}).start();
}
}
The moment you call sendRequest it would run on a separate thread. addAll & notifyDataSetChanged won't add anything cuz by the time you call them objects would still be empty
Move
adapter.addAll(objects);
adapter.notifyDataSetChanged();
to your thread's run method
Related
I have ListView which have data . Data come from server and I want the ListView to update after every 5 sec. How to do this? I am new to android development. Please help me. Here is my code..
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 data = c.getString(TAG_DATA);
final String dataaaa = rcdata.getText().toString().trim();
HashMap<String, String> user_data = new HashMap<String, String>();
user_data.put(TAG_DATA, data);
personList.add(user_data);
}
ListAdapter adapter = new SimpleAdapter(
DataSendActivity.this, personList, R.layout.layout_chat,
new String[]{TAG_DATA},
new int[]{R.id.data}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
also tried this onCreate
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 5000 );
}
}, 5000 );
i get data with this method
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
//String recID = ;
//String userID = email;
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HashMap<String, String> user = db.getUserDetails();
//String name = user.get("name");
// Semail = user.get("email");
String semail = user.get("email");
final String remail = rremail;
HttpPost httppost = new HttpPost("http://samplechatapp.gear.host/myphpfile.php?sender_email="+semail+"&reciver_email="+remail+"&fatch_server_data=true");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
Log.i("","processing entity");
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");
Log.i("",line);
}
result = sb.toString();
Log.i("",result);
} catch (Exception e) {
// Oops
} 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();
}
but when i open the listview app crash please help me i am very new in android
You should call the api after you get the response from the first api call . You can notifyDataSetChanged() post that .
Call notifyDataSetChanged() whenever there is change in data.
Moreover avoid using ListView instead of that start using RecyclerView.
I am fetching texts first and adding them to the ListView (This part is working).
Then for each item in the ListView I am fetching an image and need to add this image to the ImageView of each item which is already defined in the layout.
I am able to get all the images but don't know how to update the ListView with the same.
//AsyncTask For texts.
private class pgData extends AsyncTask<String, String, JSONArray> {
protected JSONArray doInBackground(String... params) {
publishProgress("Starting");
String result=null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xxx/xxx.php");
HttpResponse response = null;
HttpEntity httpentity =null;
JSONArray t=null;
try{
response= httpclient.execute(httppost);
httpentity=response.getEntity();
result= EntityUtils.toString(httpentity);
t=new JSONArray(result);
}catch (Exception e){
publishProgress(e.toString());
this.cancel(true);
}
return t;
}
protected void onProgressUpdate(String... i) {
Toast.makeText(getBaseContext(), i[0], Toast.LENGTH_SHORT).show();
}
protected void onPostExecute(JSONArray result) {
String x[];
l = result.length();
pg_data = new pg[l];
JSONObject jsonObject;
for (int i = 0; i < l; i++) {
try {
jsonObject = result.getJSONObject(i);
x[0] = jsonObject.getString("xxx");
x[1]=jsonObject.getString("xxx");
x[2] = jsonObject.getString("xxxx");
x[3] = jsonObject.getString("rentMonthly");
pg_data[i] = new pg(
x[0],
x[1],
x[2],
x[3]
);
jdata.add(xxx_data[i]);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
adapter = new pgAdapter(second.this,
R.layout.pg,
xxx_data);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
new xxImage().execute(); //exexuting async task for fetching images.
}
}
//Async Task for fetching images
private class xxImage extends AsyncTask<String, String, JSONArray> {
protected JSONArray doInBackground(String... params) {
publishProgress("Getting Images");
String result=null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xx/xx.php");
HttpResponse response = null;
HttpEntity httpentity =null;
JSONArray t=null;
try{
response= httpclient.execute(httppost);
httpentity=response.getEntity();
result= EntityUtils.toString(httpentity);
t=new JSONArray(result);
}catch (Exception e){
publishProgress(e.toString());
this.cancel(true);
}
return t;
}
protected void onProgressUpdate(String... i) {
Toast.makeText(getBaseContext(), i[0], Toast.LENGTH_SHORT).show();
}
protected void onPostExecute(JSONArray result) {
String image1;
l = result.length();
xx_image = new xxImage[l];
JSONObject jsonObject;
for (int i = 0; i < l; i++) {
try {
jsonObject = result.getJSONObject(i);
image1 = "\n" + jsonObject.getString("image1") + "\n";
xx_image[i] = new xxImage(
image1
);
jimage.add(xx_image[i]);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
//I got all the Images in 'jimage'. Now how to update the ListView from here?
}
}
In your second AsyncTask do the following in the loop:
parse your image after getting it in image1.
get the item at i from the adapter.
from that item find the view with its id.
set the image on it.
Done. Try, hope it works for you.
You need to implement a custom ArrayAdapter for doing this. In you first asyncTask you set the adapter using the text data that you have but the adapter that you are using is of the form
ArrayAdapter(Context context, int resource, T[] objects)
In your case T is String (as far as I can see). But you want this T to be a custom object which also includes an image. You can do this by building your own custom adapter. Have a look at this answer.
Or another way is that your T object should be something like this.
CustomObject customObject = new CustomObject(text, image).
Try creating a list of these objects which you will then pass to the adapter instead of passing just the text array. But for this you will have to wait till all the images are loaded.
A better idea is to use Picasso. And implement a custom Adapter. Your current approach is very flawed.
guys I have a problem with implement error handling in my application.
I want to display the error message to the user of my application when the response code from rest is not 200. In other words: If the connection is wrong, I want to display the message, that the user have to check his internet connection and try again. If everything is fine I want to do everything as usual so load the content.
I write something like this:
Toast errorToast = Toast.makeText(NewsActivity.this, "Error, pls chech your internet connection and try again!", Toast.LENGTH_SHORT);
errorToast.show();
and this:
if(response.getStatusLine().getStatusCode() == 200){}
But i don't know If this is good code and where should I insert it. I will be very grateful for your help and advice.
This is this code:
public class NewsActivity extends Activity {
private static final String URL = "http://10.0.2.2:8083/rest/aktualnosci";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
new FetchItems().execute();
}
private class FetchItems extends AsyncTask<String, Void, JSONArray> {
protected JSONArray doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Content-type", "application/json");
JSONArray json = new JSONArray();
try {
HttpResponse response = httpclient.execute(httpget);
json = new JSONArray(EntityUtils.toString(response.getEntity()));
return json;
}
} catch (Exception e) {
Log.v("Błędne wczytanie", e.getMessage());
}
return json;
}
protected void onPostExecute(JSONArray result) {
ListView lst = (ListView) findViewById(R.id.aktualnosci_list);
ArrayList<String> listItems = new ArrayList<String>();
String contentToEdit;
String titleContainer;
TextView newsHeaderTextView = null;
for (int i = 0; i < result.length(); i++) {
try {
titleContainer = result.getJSONObject(i).getString("title").toString();
listItems.add(titleContainer);
contentToEdit=result.getJSONObject(i).getString("body").toString();
contentToEdit= Html.fromHtml(contentToEdit).toString();
listItems.add(contentToEdit);
} catch (Exception e) {
Log.v("Błędne wczytanie1", e.getMessage());
}
}
ArrayAdapter ad = new ArrayAdapter(NewsActivity.this, android.R.layout.simple_list_item_1, listItems);
lst.setAdapter(ad);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
You can add this in doInBackground method.
runOnUiThread(new Runnable() {
public void run() {
if (response.getStatusLine().getStatusCode() != 200) {
Toast errorToast = Toast.makeText(NewsActivity.this, "Error, pls chech your internet connection and try again!", Toast.LENGTH_SHORT);
errorToast.show();
}
}
});
/*
I thought Your Code Working Fine Made Some Changes As Per Need
*/
public class NewsActivity extends Activity {
private static final String URL = "http://10.0.2.2:8083/rest/aktualnosci";
String jsonArrayString = "";
String message = "Error, pls check your internet connection and try again!";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
new FetchItems().execute(this);
}
private class FetchItems extends AsyncTask<Context,Void,String>{
Context temp;
#Override
protected String doInBackground(Context... params) {
temp = params[0];
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Content-type", "application/json");
JSONArray json = new JSONArray();
try {
HttpResponse response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200) {
json = new JSONArray(EntityUtils.toString(response.getEntity()));
jsonArrayString += json.toString();
return jsonArrayString;
}
}
catch (Exception e) {
Log.v("Błędne wczytanie", e.getMessage());
}
return message;
}
#Override
protected void onPostExecute(String s) {
ListView lst = (ListView) findViewById(R.id.aktualnosci_list);
ArrayList<String> listItems = new ArrayList<String>();
String contentToEdit;
String titleContainer;
TextView newsHeaderTextView = null;
if(!message.equals(s))
{
JSONArray result = null;
try {
result = new JSONArray(s);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < result.length(); i++) {
try {
titleContainer = result.getJSONObject(i).getString("title").toString();
listItems.add(titleContainer);
contentToEdit=result.getJSONObject(i).getString("body").toString();
contentToEdit= Html.fromHtml(contentToEdit).toString();
listItems.add(contentToEdit);
} catch (Exception e) {
Log.v("Błędne wczytanie1", e.getMessage());
}
}
ArrayAdapter ad = new ArrayAdapter(NewsActivity.this, android.R.layout.simple_list_item_1, listItems);
lst.setAdapter(ad);
}
else
{
Toast.makeText(temp,message,Toast.LENGTH_LONG).show();
}
}
}
}
I am having a problem with my setOnClickListener. I can not figure out what the code is i need for it. What i am trying to do is once the item is clicked on in the list view it opens up a new activity. in my code the list view is in the MainActivity. and i want it to open up the Homework activity. So my question is, can anybody help me figure out what i need to put in for it to work correctly and open up Homework.java? when it opens up Homework.java it would show the item clicked in the list view as the header. then nothing in the body.
MainActivity.class:
public class VideoListTask extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog;
protected void onPreExecute (Void result) {
dialog.getProgress();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params)
{
HttpClient client = new DefaultHttpClient();
//HttpGet getRequest = new HttpGet(feedUrl);
Date now = new Date();
HttpGet getRequest = new HttpGet(canvasUrl + "courses? include[]=term&state=available");
getRequest.setHeader("Authorization","Bearer " + canvasApiKey); //uses your key to access your data
try
{
HttpResponse response = client.execute(getRequest);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if(statusCode != 200)
{
return null;
}
InputStream jsonStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine())!=null)
{
builder.append(line);
}
String jsonData = builder.toString();
//JSONObject json = new JSONObject(jsonData);
//JSONObject data = json.getJSONObject("data");
//JSONArray items = data.getJSONArray("items");
JSONArray courses = new JSONArray(jsonData);
//for(int i =0; i<items.length(); i++)
//{
// JSONObject video = items.getJSONObject(i);
// videoArrayList.add(video.getString("title"));
//}
for(int i = 0; i<courses.length(); i++)
{
JSONObject course = courses.getJSONObject(i);
JSONObject term = course.getJSONObject("term");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date enddate = format.parse(term.getString("end_at"));
Date startdate = format.parse(term.getString("start_at"));
if (now.after(startdate) && now.before(enddate))
{
videoArrayList.add(course.getString("name"));
}
} catch (Exception e) {
//videoArrayList.add(course.getString("name"));//include if you want undated courses
}
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
THIS IS WHERE I NEED TO PUT THE ONCLICK LISTENER IN.
}
If Homework.java is your second activity you can set a click listener in this way
Main Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
ListView myListView = (ListView) findViewById(R.id.myListView);
myListView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
startActivity(new Intent(MainActivity.this, Homework.class));
}
});
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Class<?> ourClass=Class.forName("com.example.projname.Homework");
Intent ourIntent= new Intent(MainActivity.this,ourClass);
ourIntent.putExtra("matrix", m);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
});
The data you pass using putExtra will be available to you in the Homeactivity.java
I have a problem with making an new ArrayAdapter for a spinner in a android java thread. I cannot make this work because the thread has no link to my main class. I found on the Internet that instead of using a thread, I need to use an AsyncTask but for one reason I cannot get the principal of this. So I would like to know how I can solve this.
public void connect() throws InterruptedException
{
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet("http://192.168.1.118:8080/quiz/output.php");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
//Log.i("Info",response.getStatusLine().toString()); Comes back with HTTP/1.1 200 OK
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
jsonArray = new JSONArray(result);
instream.close();
}
} catch (Exception e) {
Log.e("Error",e.toString());
}
}
});
Thread thread2 = new Thread(new Runnable(){
#Override
public void run() {
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
try {
JSONObject item = jsonArray.getJSONObject(i);
String ID = item.getString("groepID");
String groepNaam = item.getString("groepNaam");
Log.e("string", "groepid = " + ID + " " + groepNaam);
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectgroep.setAdapter(dataAdapter);
}
});
thread.start();
thread.join();
thread2.start();
}
The error is with the following code:
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
Would anyone know how I can solve this issue?
Much appreciation,
Thomas Thooft
Use the activity's class in front of this:
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MyActivity.this,
android.R.layout.simple_spinner_item, list);
Read more about this here: Java: Class.this