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
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 have a problem with some information downloaded from a DDBB. I recieve all the information, but I can't store it on my arrays because the onPostExecute() method doesn't starts. I put my code:
RequestRocodromo.java, is the class for making the request and recieve the information, on "results" variable I have all the information, but I can't storage it on the arrays of onPostExecute():
#Override
protected JSONObject doInBackground(String... params)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(_url);
String results = "NO OK";
try
{
// Add your data
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("mac", _mac ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));*/
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
response.getAllHeaders();
response.getEntity();
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
results = EntityUtils.toString(response.getEntity());
}
broadcastIntent = new Intent();
broadcastIntent.putExtra("correcto", results);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject jsonResponse)
{
super.onPostExecute(jsonResponse);
List<String> values = new ArrayList<String>();
ArrayList<String> rocodromoId = new ArrayList<String>();
ArrayList<String> rocodromoArray = new ArrayList<String>();
ArrayList<String> ciudadArray = new ArrayList<String>();
ArrayList<String> comentarioArray = new ArrayList<String>();
//Procesamos los resultados
try
{
if(jsonResponse != null)
{
JSONArray jsonMainNode =jsonResponse.optJSONArray("edificios");
int lengthJsonArr =jsonMainNode.length();
for(int i=0; i<lengthJsonArr; i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
rocodromoId.add(jsonChildNode.optString("id"));
rocodromoArray.add(jsonChildNode.optString("nombre"));
ciudadArray.add(jsonChildNode.optString("ciudad"));
comentarioArray.add(jsonChildNode.optString("comentario"));
values.add(jsonChildNode.optString("nombre"));
}
}
String result[] = values.toArray(new String[values.size()]);
broadcastIntent = new Intent();
broadcastIntent.putExtra("edificios", result);
broadcastIntent.putStringArrayListExtra("id_rocodromo", rocodromoId);
broadcastIntent.putStringArrayListExtra("rocodromoArray", rocodromoArray);
broadcastIntent.putStringArrayListExtra("ciudadArray", ciudadArray);
broadcastIntent.putStringArrayListExtra("comentarioArray", comentarioArray);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
catch (Exception e)
{
String result = "null";
broadcastIntent = new Intent();
broadcastIntent.putExtra("edificios", result);
broadcastIntent.putStringArrayListExtra("id_rocodromo", rocodromoId);
broadcastIntent.putStringArrayListExtra("rocodromoArray", rocodromoArray);
broadcastIntent.putStringArrayListExtra("ciudadArray", ciudadArray);
broadcastIntent.putStringArrayListExtra("comentarioArray", comentarioArray);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
}
Rocodromo.java, here is where I start the execute method:
RequestRocodromo re = new RequestRocodromo(ctx, finalURL + "request=1");
re.execute("");
Rocodromo.java, here is my broadcast, when I try to obtain the arraylist information I recieve a nullException, because my arraylist are null because it never starts the onPostExecute() method.
public class ReceptorBroadcast extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent intent)
{
if(RequestRocodromo.ACTION_REQUEST_ROCODROMO.equals(intent.getAction()))
{
idRocodromo = intent.getStringArrayListExtra("id_rocodromo");
Toast.makeText(getApplicationContext(), idRocodromo.get(0).toString(), Toast.LENGTH_LONG).show();
rocodromo = intent.getStringArrayListExtra("rocodromoArray");
Toast.makeText(getApplicationContext(), rocodromo.get(0).toString(), Toast.LENGTH_LONG).show();
ciudad = intent.getStringArrayListExtra("ciudadArray");
Toast.makeText(getApplicationContext(), ciudad.get(0).toString(), Toast.LENGTH_LONG).show();
comentario = intent.getStringArrayListExtra("comentarioArray");
Toast.makeText(getApplicationContext(), comentario.get(0).toString(), Toast.LENGTH_LONG).show();
}
}
}
Can someone help my with that? Thanks! :)
Change on doInBackGround return null to:
try {
return new JSONObject(reusults);
} catch (Throwable t) {
return null;
}
Change you broadcast receiver call in your doInBackground().. as
runOnUiThread(new Runnable() {
#Override
public void run() {
broadcastIntent = new Intent();
broadcastIntent.putExtra("correcto", results);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
});
and check null result in onPostExecute as..
if(null!=jsonResponse) // avoids null pointer;
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