android how to make ListView refresh every 5 sec - java

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.

Related

AsyncTask with ArrayList as return type

I am trying to return an ArrayList from an AsyncTask. But in main activity i am not able to get the returned arraylist. I want to know the way to call the asynctask so that i can get the returned arraylist.
This is the AsyncTask -
public class GetBannerDB extends AsyncTask<Void, Void, ArrayList<String>> {
GetBannerDB() {
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
InputStream is = null;
ArrayList<String> bannerList = new ArrayList<String>();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", "data"));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url to fetch data");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
serverResult = sb.toString().trim();
try {
String sResult = serverResult.substring(0, 7);
if (sResult.equalsIgnoreCase("success")) {
// Creating user login session
// Use user real data
String[] temp = serverResult.split("\\^");
String banner_image = temp[1];
String banner_redirect = temp[2];
bannerList.add(banner_image);
bannerList.add(banner_redirect);
} else {
}
} catch (NullPointerException ex) {
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bannerList;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
mBannerTask = null;
}
}
In MainActivity, i am calling the output as --
ArrayList<String> adDetails = new ArrayList<>();
mBannerTask = new GetBannerDB();
adDetails = mBannerTask.execute();
But here i am getting error - Incompatible types.
Where m i going wrong pls guide.
Ashok as per your answer, i have done the following changes --
OnDataListener.java (As interface)
public interface OnDataListener {
void setData(ArrayList<String> result);
}
In MainActivity.java -
public class PushAds implements OnDataListener{
String serverResult = null;
private GetBannerDB mBannerTask = null;
ArrayList<String> adDetails = new ArrayList<>();
public void displayAds()
{
mBannerTask = new GetBannerDB(new OnDataListener {
public void setData(ArrayList<String> result){
adDetails = result;
}
});
mBannerTask.execute();
}
......
}
But its giving error.
public interface OnDataListner{
void setData(ArrayList<String> result);
}
and
public class GetBannerDB extends AsyncTask<Void, Void, ArrayList<String>> {
public OnDataListner dataListner;
GetBannerDB(OnDataListner dataListner) {
this.dataListner = dataListner;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
dataListner.setData(result);
}
}
finally
ArrayList<String> adDetails = new ArrayList<>();
mBannerTask = new GetBannerDB(new OnDataListner{
#Overrid
public void setData(ArrayList<String> result){
adDetails = result;
//do something
}
});
mBannerTask.execute();

Fetch sms From phone and upload on server

Here i am fetch sms from phone and upload 10 sms on server all code working fine but instead of 10 sms upload to server only Specific one sms uploaded 10 time to server, pls tell me what i am missing in my code?
here is my message_class.Java code.
public class message_class extends Activity{
int j = 0;
Button btninbox;
ListView lstView;
SimpleCursorAdapter adapter;
ArrayList<Message_Item> msg_list;
String Str_Msg, Str_Phone,dated;
Msg_adapter msg_adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msginbox_layout);
msg_list = new ArrayList<Message_Item>();
btninbox = (Button) findViewById(R.id.btn_inbox);
btninbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(message_class.this, Msg_Recive.class);
startActivity(intent);
}
});
lstView = (ListView) findViewById(R.id.lv_msg);
fetchInbox();
final int arraysize = msg_list.size();
for (int j=0; j<10;j++){
Str_Msg = msg_list.get(j).getStrMsg().toString();
Str_Phone = msg_list.get(j).getStrNumber().toString();
Toast.makeText(message_class.this, Str_Phone+" "+Str_Msg, Toast.LENGTH_LONG).show();
new HttpAsyncTask()
.execute("http://demo.glowsosl.com/synchs_dsda_app/insert_details_msg.php");
msg_adapter.notifyDataSetChanged();
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result + "Data Sent!",
Toast.LENGTH_LONG).show();
}
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public static String POST(String url, Contacts person) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("contact_no", person.getPhone());
jsonObject.accumulate("sim_num", "Unknown");
jsonObject.accumulate("msg", person.getName());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result + "," + person.getName() + ","
+ person.getPhone();
}
ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
return stringArray;
}
public void fetchInbox() {
// ArrayList sms = new ArrayList();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms,
new String[] { "_id", "address", "date", "body" }, null, null,
null);
//for (int i =0; i<((JSONArray) cursor).length();i++){
//Toast.makeText(getApplicationContext(), "work", Toast.LENGTH_SHORT).show();
//}
cursor.moveToFirst();
while (cursor.moveToNext()) {
String address = cursor.getString(1);
String date = cursor.getString(2);
String body = cursor.getString(3);
// Toast.makeText(getApplicationContext(), cursor.getString(2), Toast.LENGTH_SHORT).show();
msg_list.add(new Message_Item(address, body,date));
}
msg_adapter = new Msg_adapter(msg_list, message_class.this);
lstView.setAdapter(msg_adapter);
}
Instead of applying for loop out side async task use it in doInBackground method.
Your doInBackground method will look like follows.
#Override
protected String doInBackground(String... urls) {
String result="";
for(int i = 0; i < msg_list.size(); i++){
Str_Msg = msg_list.get(i).getStrMsg().toString();
Str_Phone = msg_list.get(i).getStrNumber().toString();
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
result= result + POST(urls[0], person);
}
return result;
}
And call this async task only once.
Enjoy!!

How to start an Activity from AsyncTask?

I've build an AsyncTask and want to start another Activity when it ends (onPostExecute) but it won't work and I can't find the problem. Maybe there is a problem with String, String, String ?
Here is my code:
public class StartSearch extends AsyncTask<String, String, String> {
private Activity activity;
#Override
protected String doInBackground(String... strings) {
StringBuilder sb = new StringBuilder();
String http = "https://list-creater-service.herokuapp.com/api/v1/search";
HttpURLConnection urlConnection = null;
JSONObject json = null;
HttpResponse response = null;
try {
//connect to server
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Host", "list-creater-service.herokuapp.com");
urlConnection.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("gamemode", gametype);
jsonParam.put("country", selCountry);
jsonParam.put("min_size", minSize);
jsonParam.put("max_size", maxSize);
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
int HttpResult = urlConnection.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(),"utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String jsonS = sb.toString();
JSONArray jsonArray = new JSONArray(jsonS);
int length = jsonArray.length();
String[] names = new String[length];
for (int i = 0; i < length; i++) {
JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
ArrayList serverList = new ArrayList();
serverList.add(jsonObject.getString("name"));
serverData = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = serverData.edit();
Set<String> set = new HashSet<String>();
set.addAll(serverList);
editor.putStringSet("name", set);
editor.commit();
System.out.println(jsonObject.getString("name"));
names[i] = jsonObject.getString("name");
}
//String name = jsonObject.getString("name");
System.out.println("" + sb.toString());
}else{
System.out.println(urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(urlConnection!=null)
urlConnection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
activity.startActivity(new Intent(activity, ServerIndex.class));
}
}
Need some help!
Thx :)
You have Activity activity declared , but you have not assigned your current activity context to it . Assign the current activity context to it.
Like
activity=currentContext;
You should use runOnUIThread in your onPostExecute
runOnUiThread(new Runnable() {
public void run() {
activity.startActivity(new Intent(activity, ServerIndex.class));
}});
And as Raghunandan said, activity is not initialized. You can access the startActivity method from your StartSearch class by using
SomeActivity.this.startActivity (SomeActivity has to be initialized)
And since onPostExecute runs on the UI thread, you may or may not call runOnUIThread.

Java: Can't convert string to array

I can't convert a string to an array!
String text = "";
String[] textsplit = {};
//Stuff
The app set the content of an online txt file in a string:
The online txt file contain: hello,my,name,is,simone
[...] //Downloading code
text = bo.toString(); //Set the content of the online file to the string
Now the string text is like this:
text = "hello,my,name,is,simone"
Now i have to convert the string to an array that must be like this:
textsplit = {"hello","my","name","is","simone"}
so the code that i use is:
textsplit = text.split(",");
But when i try to use the array the app crash! :(
For example:
textview.setText(textsplit[0]); //The text of the textview is empity
textview.setText(textsplit[1]); //The app crash
textview.setText(textsplit[2]); //The app crash
etc...
where am I wrong? thanks!
EDIT: This is the code:
new Thread() {
#Override
public void run() {
String path ="http://www.luconisimone.altervista.org/ciao.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
text = bo.toString();
testo.setText("(" + text + ")");
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
// Here all variables became empity
textsplit = text.split(",");
datisplittati.setText(textsplit[0]);
Try :
String text = "hello,my,name,is,simone";
String[] textArr = text.split(Pattern.quote(","));
You can get string using AsyncTask
private class GetStringFromUrl extends AsyncTask<String, Void, String> {
ProgressDialog dialog ;
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progress dialog when downloading
dialog = ProgressDialog.show(MainActivity.this, null, "Downloading...");
}
#Override
protected String doInBackground(String... params) {
// #BadSkillz codes with same changes
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(entity);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
String result = total.toString();
Log.i("Get URL", "Downloaded string: " + result);
return result;
} catch (Exception e) {
Log.e("Get Url", "Error in downloading: " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO change text view id for yourself
TextView textView = (TextView) findViewById(R.id.textView1);
// show result in textView
if (result == null) {
textView.setText("Error in downloading. Please try again.");
} else {
textView.setText(result);
}
// close progresses dialog
dialog.dismiss();
}
}
and use blow line every time that you want:
new GetStringFromUrl().execute("http://www.luconisimone.altervista.org/ciao.txt");
You're using new thread to get data from an url. So in runtime, data will be asynchronous.
So when you access text variable (split it), it's still not get full value (example reason: network delay).
Try to move the function split after text = bo.toString(); , I think it will work well.

I can't get my ListFragment to Display data android

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

Categories