I am trying to make strings in the text view clickable.My textview consists of name of various online questions and i want them to redirect the user to the url of the question when clicked.Can anyone recommend changes to my code.
In the following code "result" is the final textview consisting of name of questions .
public class Http extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://codeforces.com/api/user.status?handle=";
String m = "";
public static String[] sarr = new String[200];
public static String[] name = new String[200];
public static int cnt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView)findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("result");
}
public JSONObject lastSub(String username) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
int status = 0;
HttpResponse r = client.execute(get);
status = r.getStatusLine().getStatusCode();
if(status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject last = new JSONObject(data);
//JSONObject last = new JSONObject(data).getJSONArray("result").getJSONObject(0).getJSONObject("problem");
return last;
}
else {
Toast.makeText(Http.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask <String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
String add = "&from=1&count=100";
String input = (Mainapp.p);
input = input.concat(add);
json = lastSub(input);
JSONArray array = json.getJSONArray("result");
String m1=null, m2=null, m3=null;
String n1 = System.getProperty("line.separator");
int flag=0;
for(int k=0; k<array.length() && cnt<15; k++)
{
JSONObject json1 = array.getJSONObject(k).getJSONObject("problem");
JSONObject v = array.getJSONObject(k);
if(v.getString("verdict").contentEquals("OK")) {
m1 = json1.getString("name");
m2= json1.getString("contestId");
m2= m2.concat("/");
m3= json1.getString("index");
m2 = m2.concat(m3);
flag = 0;
for(int i=0; i<cnt ; i++) {
if (sarr[i].equals(m1)) {
flag = 1;
}
}
if(flag == 0) {
m = m.concat(m1);
m= m.concat(n1);
sarr[cnt] = m1;
name[cnt] = m2;
cnt++;
}
}
}
return m;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
return "INVALID USER NAME";
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
httpStuff.setText(result);
}
}
}
}
You want to use question name as hyperlink
String html = "<html> Visit Question1 </html>";
textview.setText(Html.fromHtml(html));
textview.setMovementMethod(LinkMovementMethod.getInstance());
This code allows you to not only make links clickable but also # and # are clickable
Create a new file called InternalURLSpan.java and paste this code into it:
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
public class InternalURLSpan extends android.text.style.ClickableSpan {
public String text;
public static Context context;
public InternalURLSpan(Context contex){
this.context = context;
}
#Override
public void onClick(View widget) {
handleLinkClicked(text, widget.getContext());
}
public void handleLinkClicked(String value, Context context) {
if (value.startsWith("http")) {
// Open the url with the default webpage
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(value));
context.startActivity(i);
} else if (value.startsWith("#")) {
value = value.replace("#", ""); //To get the text without the #
System.out.println(value);
} else if (value.startsWith("#")) {
value = value.replace("#", ""); //To get the text without the #
System.out.println(value);
}
}
}
paste this in a class (can be the same)
void setLinks(TextView tv, String text) {
String[] linkPatterns = {
"([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\">\\]\\)]*[^\\. ,'\">\\]\\)])",
"#[\\w]+", "#[\\w]+" };
for (String str : linkPatterns) {
Pattern pattern = Pattern.compile(str);
Matcher matcher = pattern.matcher(tv.getText());
while (matcher.find()) {
int x = matcher.start();
int y = matcher.end();
final android.text.SpannableString f = new android.text.SpannableString(
tv.getText());
InternalURLSpan span = new InternalURLSpan(context);
span.text = text.substring(x, y);
f.setSpan(span, x, y,
android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(f);
// tv.setOnLongClickListener(span.l);
}
}
tv.setLinkTextColor(Color.BLUE);
tv.setLinksClickable(true);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setFocusable(false);
}
Then use this:
setLinks(textView, "THE TEXT WHERE THE LINK IS IN, FOR EX. http://www.google.nl will be underlined and clickable #this_will_also_be_clickable #this_is_clickable_too");
Related
hello i want to get string from activity and set it to the another non activity class please help me i am adding my code.and i need to set the edittext value in non activity class url. help me
my activity.
public class AlertForIp extends AppCompatActivity {
String value;
private Button mButton;
final Context c = this;
static String urlString;
private static AlertForIp instance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
instance = this;
final EditText input = new EditText(AlertForIp.this);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertForIp.this);
//AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
/* SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(AlertForIp.this);
final SharedPreferences.Editor editor = prefss.edit();*/
value = input.getText().toString();
// Setting Dialog Title
String urlsss="http://";
String urls=":1219/Json/Handler.ashx";
// This above url string i need to set in that class
urlString = urlsss+value+urls;
/* editor.putString("stringid", urlString); //InputString: from the EditText
editor.commit();
*/
alertDialog.setTitle("WELCOME TO RESTROSOFT");
// Setting Dialog Message
alertDialog.setMessage("ENTER YOUR IP");
//final EditText input = new EditText(this);
//alertDialog.setView(input);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
//input.setText("http://");
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
android.text.Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart)
+ source.subSequence(start, end)
+ destTxt.substring(dend);
if (!resultingTxt
.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
return "";
} else {
String[] splits = resultingTxt.split("\\.");
for (int i = 0; i < splits.length; i++) {
if (Integer.valueOf(splits[i]) > 255) {
Toast.makeText(AlertForIp.this, "Please enter valid ip", Toast.LENGTH_SHORT).show();
return "";
}
}
}
}
return null;
}
};
input.setFilters(filters);
//input.setText(ip);
alertDialog.setView(input); //
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.waiting);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
/*if(input.getText().length()==0)
{
input.setError("Field cannot be left blank.");
dialog.dismiss();
}*/
String validation="^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?";
if (value.matches(validation))
{
Toast.makeText(getApplicationContext(),"enter valid IP address",Toast.LENGTH_SHORT).show();
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
// or
}
else if(!input.getText().toString().equals(""))
{
Intent intent = new Intent(AlertForIp.this, Sample.class);
startActivity(intent);
//Toast.makeText(AlertDialogForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else
{
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
Toast.makeText(AlertForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
//dialog.cancel();
finish();
}
});
// closed
// Showing Alert Message
alertDialog.show();
}
public static Context getContext() {
RestAPI rss=new RestAPI();
rss.persistItems(urlString);
return instance.getApplicationContext();
}
}
And here is my no activity class
public class RestAPI {
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
This is my another Activity i have created the instance of restApi
public class UserDetailsActivity extends Activity {
TextView tvFisrtName, tvLastName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
// Show the Up button in the action bar.
//setupActionBar();
tvFisrtName=(TextView)findViewById(R.id.tv_firstname);
tvLastName=(TextView)findViewById(R.id.tv_lastname);
Intent i=getIntent();
String username=i.getStringExtra("User_Name");
new AsyncUserDetails().execute(username);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
protected class AsyncUserDetails extends AsyncTask<String,Void,JSONObject>
{
String str1;
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonObj = null;
//here i have error
RestAPI api = new RestAPI();
try {
jsonObj = api.GetUserDetails(params[0]);
//JSONParser parser = new JSONParser();
//userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
try {
JSONObject jsonObj=result.getJSONArray("Value").getJSONObject(0);
str1=jsonObj.getString("user_id").toString();
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(UserDetailsActivity.this, str1, Toast.LENGTH_SHORT).show();
tvFisrtName.setText(str1);
}
}
public class RestAPI {
String url;
// create constructor here
public RestAPI(String url){
this.url=url;
}
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
now you can use here url directly
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
use here
RestAPI rss=new RestAPI(urlString );
"http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings" - Link Which Iam Trying to parse
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WebServer Request URL
String serverURL = "http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView uiUpdate = (TextView) findViewById(R.id.textView2);
TextView jsonParsed = (TextView) findViewById(R.id.textView3);
int sizeData = 0;
EditText serverText = (EditText) findViewById(R.id.textView);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try {
// Set Request parameter
data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e) {
Error = e.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : " + Error);
}else
{
//Show Response Json Onscreen(Activity)
uiUpdate.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
try {
JSONObject jsono = new JSONObject(Content);
JSONObject mainObject = jsono.getJSONObject("data");
JSONArray jsonArray = mainObject.getJSONArray("standing");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
// get details2 JSONObject
String position = object.optString("position").toString();
String team = object.optString("team").toString();
OutputData += "Position: " + position + " "
+ "Team Name : " + team + " ";
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
jsonParsed.setText( OutputData );
}catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
**I am Creating a premier league application which shows all the datas needed for a premier league fan. As Iam new to this I am getting confused over json parsing and getting data from apis. So Can anyone Explain to me how to change my code or Some links which would help me correct it.
Above given is my java code of Main Activity.**
Thank You Everyone for Helping out. But I found my answer from the search over the internet. Here I used VOLLEY to call the link.
JSON PARSER CLASS
public class ParseJSON {
public static String[] position1;
public static String[] team;
public static String[] points;
public static final String JSON_ARRAY = "data";
public static final String CHILD_ARRAY = "standings";
public static final String KEY_ID = "position";
public static final String KEY_NAME = "team";
private JSONObject users = null;
private JSONArray user2=null;
private JSONObject user3=null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONObject(JSON_ARRAY);
try {
user2=users.getJSONArray(CHILD_ARRAY);
position1 = new String[user2.length()];
team = new String[user2.length()];
points=new String[user2.length()];
for (int i = 0; i < user2.length(); i++) {
JSONObject jo = user2.getJSONObject(i);
try {
user3=jo.getJSONObject("overall");
points[i] = user3.getString("points");
System.out.println("Message me: "+points[i]);
}catch (Exception e)
{
e.printStackTrace();
}
position1[i] = jo.getString(KEY_ID);
team[i] = jo.getString(KEY_NAME);
System.out.println("Message me: "+position1[i]);
System.out.println("Message me: "+team[i]);
}
}catch (Exception e)
{
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Main Activity Class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String JSON_URL="http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
private Button buttonGet;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonGet.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listView);
}
#Override
public void onClick(View v) {
sendRequest();
}
private void sendRequest() {
final StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.position1,ParseJSON.team,ParseJSON.points);
listView.setAdapter(cl);
}
}
Custom Class for adding datas to list view
public class CustomList extends ArrayAdapter<String> {
private String[] position1;
private String[] team;
private String[] points;
private Activity context;
public CustomList(Activity context, String[] position1, String[] team, String[] points) {
super(context, R.layout.list_view_layout, position1);
this.context = context;
this.position1 = position1;
this.team = team;
this.points = points;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView pos1 = (TextView) listViewItem.findViewById(R.id.position1);
TextView teamname = (TextView) listViewItem.findViewById(R.id.teamname);
TextView points1 = (TextView) listViewItem.findViewById(R.id.points);
pos1.setText("Position: "+position1[position]);
teamname.setText("Team: "+team[position]);
points1.setText("Points: "+points[position]);
return listViewItem;
}
}
Step 1 : Use Retroft + RxJava for Asynchronous API calls
Step 2 : Use Gson to Serialize and Deserialize.
Step 3 : Use json to POJO to have a Model Class
Simplify the code.
Hi I don't know asking proper question or not but i want to develop Like Comment on Facebook post, Update comment and Delete Comment.
When i will add comment it will send request to server and it will give response with new values to fill in listadapter and that change may appear on my listview after click on enter or add button, and on delete it will send request to server and in response fill my listAdapter. and change may appear on my listview without refreshing listview. how can i perform this operation .
Thank You in Adavance.
Here is my Class.
public class CommmentActivity extends Activity{
DatabaseHandler db = new DatabaseHandler(this);
List<CommentListInfo> list_CommentInfo = new ArrayList<CommentListInfo>();
List<String> SuggetionList;
AutoCompleteTextView aCompletView;
EditText etComment;
String strComment;
ArrayAdapter<String> mentionList;
ListCommentAdapter commentAdapter;
ImageView IvAddComment;
ListView CommentList;
SessionCreator m_session;
boolean m = false;
boolean mBuzy;
int FirstPosition;
int ItemCounted;
int CurrentScrollState;
int TotalItemCount;
String UserId;
String VidoId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.commentvideo_main);
SuggetionList = new ArrayList<String>();
String Curl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo";
Intent data = getIntent();
UserId = data.getStringExtra("userId");
VidoId = data.getStringExtra("videoId");
init();
String strfriendsSyncDate = m_session.getfriendsSyncDate();
Log.d("mData", strfriendsSyncDate);
new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,Curl,"1");
commentAdapter = new ListCommentAdapter(getApplicationContext(), list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:{
commentAdapter.notifyDataSetChanged();
//ManipulateVisibleView(view);
break;
}
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
{
mBuzy = true;
break;
}
case OnScrollListener.SCROLL_STATE_FLING:{
mBuzy = true;
break;
}
default:
break;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
FirstPosition = firstVisibleItem;
ItemCounted = visibleItemCount;
TotalItemCount = totalItemCount;
int LastPosition = view.getLastVisiblePosition();
Log.d("First Position", ""+FirstPosition);
Log.d("ItemCountes",""+ItemCounted);
Log.d("totalItemCount",""+TotalItemCount);
Log.d("LastPosition",""+LastPosition);
if(visibleItemCount!=0 && ((firstVisibleItem+visibleItemCount)>=(totalItemCount))){
Log.d("mCalled", "call");
}
isScrollCompleted();
}
});
IvAddComment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
strComment = etComment.getText().toString();
etComment.getText().clear();
String strUrl = GlobalMethod.TokenGenerator() + "&action=addCommentsVideo";
new CommentsDetail().execute(UserId,VidoId,strComment,strUrl,"0");
commentAdapter.notifyDataSetChanged();
}
});
}
private void isScrollCompleted(){
if(this.ItemCounted >0 && this.CurrentScrollState == OnScrollListener.SCROLL_STATE_IDLE){
Log.d("ItemCounted",""+ItemCounted);
Log.d("CurrentScrollState",""+CurrentScrollState);
}
}
private void init() {
// TODO Auto-generated method stub
m_session = new SessionCreator(getApplicationContext());
etComment = (EditText)findViewById(R.id.etComments);
CommentList = (ListView)findViewById(R.id.lvLatestComments);
IvAddComment = (ImageView)findViewById(R.id.addComment);
}
public class CommentsDetail extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ServiceHandler serviceClient;
String mJsonString;
try{
String userId = (String)params[0];
String vId = (String)params[1];
if(params[4].equals("0")){
String comment = (String)params[2];
String strUrl = (String)params[3];
List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();
paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
paramsNameValuePairs.add(new BasicNameValuePair("commentText", comment));
serviceClient = new ServiceHandler();
mJsonString = serviceClient.makeServiceCall(strUrl,
ServiceHandler.POST, paramsNameValuePairs);
Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
}else{
String syncdate = (String)params[2];
String strUrl = (String)params[3];
List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();
paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
paramsNameValuePairs.add(new BasicNameValuePair("friendsSyncDate", syncdate));
serviceClient = new ServiceHandler();
mJsonString = serviceClient.makeServiceCall(strUrl,
ServiceHandler.POST, paramsNameValuePairs);
Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
}
Log.d("Response Json-----------------------",mJsonString );
return mJsonString;
}catch (Exception e) {
e.getStackTrace();
}
return null;
}
#SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
if (result != null) {
JSONObject responsJsonObj = new JSONObject(result);
JSONObject jsonObj = (JSONObject) responsJsonObj
.optJSONObject("data");
try {
String str = jsonObj.getString("error");
if ( str != null || str.length() != 0) {
// error
//Toast.makeText(NewsfeedActivity.this, jsonObj.getString("error"),Toast.LENGTH_LONG).show();
return;
}
} catch (JSONException je) {
Log.d("jex ------>", "" + je.getMessage());
try {
String str = jsonObj.getString("message");
Log.d("message=", "" + str);
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("comments")) {
JSONArray colArray = jsonObj.getJSONArray("comments");
Log.d("Colunm Array", ""+colArray);
int nComments = colArray.length();
Log.d("# comments", "" + nComments);
for(int i=0; i<nComments; i++){
JSONObject obj = colArray.getJSONObject(i);
Gson Comments = new Gson();
String strComments = Comments.toJson(obj);
Log.d("# obj=", "" + obj.toString());
CommentListInfo cmtInfo = new CommentListInfo();
cmtInfo.c_userId = obj.getString("userId");
cmtInfo.c_name = obj.getString("name");
cmtInfo.DateAdded = obj.getString("dateAdded");
cmtInfo.CommentId = obj.getString("commentId");
cmtInfo.CommentText = obj.getString("text");
cmtInfo.ImageUrl = obj.getString("imageLink");
list_CommentInfo.add(cmtInfo);
}
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("addPosition")) {
Log.d("# obj=", "" + jsonObj.toString());
Log.d("Add Position", jsonObj.getString("addPosition"));
}
}
//
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("friendsSyncDate")) {
Log.d("# friendsDeleted", "" + jsonObj);
Log.d("# obj=", "" + jsonObj.toString());
String myString = m_session.getfriendsSyncDate();
Log.d("myString", myString);
m_session.putfriendsSyncDate(jsonObj.getString("friendsSyncDate"));
Log.d("Sync Date "," "+jsonObj.getString("friendsSyncDate"));
}
}
} catch (JSONException je2) {
je2.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Here is my Adapter Class.
public class ListCommentAdapter extends BaseAdapter{
private Context mContext;
private List<CommentListInfo> CommentsInfo;
private LayoutInflater inflater;
private String szUserId;
private String szVideoID;
private boolean mBuzy = false;
public ListCommentAdapter(Context context, List<CommentListInfo> cmtInfo) {
// TODO Auto-generated constructor stub
mContext = context;
CommentsInfo = cmtInfo;
AppData mmap = (AppData)this.mContext.getApplicationContext();
szUserId = mmap.getUserId();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return CommentsInfo.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return CommentsInfo.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
CommentListInfo c = CommentsInfo.get(position);
try{
Log.i("nUserId", c.c_userId);
Log.i("nName", c.c_name);
Log.i("nCommentId", c.CommentId);
Log.i("nCommnet", c.CommentText);
Log.i("nImageUrl",c.ImageUrl);
}catch(Exception e){
Log.e("Erore is",""+e);
}
try{
if(inflater==null){
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null){
convertView = inflater.inflate(R.layout.comment_list_item, null);
holder.ciProfileImage = (CircleImageView)convertView.findViewById(R.id.civCFLeftPic);
holder.tvComments = (TextView)convertView.findViewById(R.id.tvCommentbox);
holder.tvCDate = (TextView)convertView.findViewById(R.id.tvCfNotifyDate);
holder.tvName = (TextView)convertView.findViewById(R.id.tvCommentName);
convertView.setTag(holder);
}else{
holder = (Holder)convertView.getTag();
}
if(!mBuzy){
RemoteImageLoader task = new RemoteImageLoader();
task.setImageView(holder.ciProfileImage);
task.execute(c.ImageUrl);
Log.d("ImagerUrl", c.ImageUrl);
if(c.ImageUrl!=null){
Picasso.with(mContext)
.load(R.drawable.world1)
.placeholder(R.drawable.world1)
.error(R.drawable.world1)
.into(holder.ciProfileImage);
}else{
Picasso.with(mContext)
.load(R.drawable.world1)
.placeholder(R.drawable.world1)
.error(R.drawable.world1)
.into(holder.ciProfileImage);
}
holder.tvComments.setText(c.CommentText);
holder.tvCDate.setText(c.DateAdded);
holder.tvName.setText(c.c_name);
holder.tvComments.setTag(null);
}else{
holder.tvComments.setText("Loading...");
holder.tvComments.setTag(this);
}
return convertView;
}catch(Exception e){
System.out.println("Error IS :- "+ e);
}
return convertView;
}
private static class Holder{
private TextView tvName,tvComments,tvCDate;
private CircleImageView ciProfileImage;
}
}
You might have solved this already but I was working on a different app in Java and came across something similar. Mine was a bit simpler because I am using a local database but ~same thing. In your CommmentActivity's onCreate method pull out the commentAdapter declaration and the CommentList.setOnScrollListener and put them in their own method. Then call your newly defined commentAdapter method in onCreate and after you parse through the response.
Something like this
public void myAdaperMethod(Context context, List<CommentListInfo> list_CommentInfo){
commentAdapter = new ListCommentAdapter(this, list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener(){...}
}
onCreate{
myAdapterMethod(...);
}
post{...}
get{myAdapterMethod(...);}
Hope that helps.
You just need to re-bind your control after the listadapter has the new dataset.
CommentList.DataBind();
my listview repeat data some time which click on buttons fastly what do i do please help me see this images http://imgur.com/ed5uDtp after some time is show like this http://imgur.com/jAt4yn7
is show correctly data on listview but some time when click fastly buttons is load duplicate data how i will fixed this? plaa help me
public class thirdstep extends Activity implements View.OnClickListener {
int count = 0;
String id;
String title;
String tmpString, finaldate;
String valll;
ProgressBar prgLoading;
TextView txtAlert;
int IOConnect = 0;
String mVal9;
Button e01;
Button e02;
Button e03;
Button e04;
Button e05;
String SelectMenuAPI;
String url;
String URL;
String URL2, URL3, URL4;
String menu_title;
JSONArray school;
ListView listCategory;
String status;
String School_ID;
String Menu_ID;
String School_name;
String Meal_groupid;
String _response;
String _response2;
String CategoryAPI;
String SelectMenuAPI2;
TextView menu_nametxt;
thirdstepAdapter cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> school_name = new ArrayList<String>();
static ArrayList<String> menu_name = new ArrayList<String>();
static ArrayList<String> dish_name = new ArrayList<String>();
static ArrayList<String> dish_ID = new ArrayList<String>();
static ArrayList<String> day = new ArrayList<String>();
static ArrayList<Long> Vacation_ID = new ArrayList<Long>();
static ArrayList<String> Vacation_name = new ArrayList<String>();
static ArrayList<String> Vacation_Date = new ArrayList<String>();
String mydate;
String mode;
String s2;
ArrayList<String> myList,myList2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
listCategory = (ListView) findViewById(R.id.thirdscreenlist);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
e01 = (Button) findViewById(R.id.e01);
e02 = (Button) findViewById(R.id.e02);
e03 = (Button) findViewById(R.id.e03);
e04 = (Button) findViewById(R.id.e04);
e05 = (Button) findViewById(R.id.e05);
e01.setOnClickListener(this);
e02.setOnClickListener(this);
e03.setOnClickListener(this);
e04.setOnClickListener(this);
e05.setOnClickListener(this);
cla = new thirdstepAdapter(thirdstep.this);
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(thirdstep.this, fifthscreen.class);
startActivity(intent);
}
});
new getDataTask().execute();
}
void clearData() {
Category_ID.clear();
school_name.clear();
menu_name.clear();
dish_name.clear();
dish_ID.clear();
day.clear();
Vacation_ID.clear();
Vacation_name.clear();
Vacation_Date.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
if (!prgLoading.isShown()) {
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if ((Category_ID.size() > 0) || IOConnect == 0) {
listCategory.setAdapter(cla);
cla.notifyDataSetChanged() ;
listCategory.invalidateViews();
} else {
txtAlert.setVisibility(0);
menu_nametxt.setText("");
listCategory.setVisibility(View.GONE);
}
}
}
public void parseJSONData() {
clearData();
SelectMenuAPI="";
SelectMenuAPI = Utils.Schoolmenu +Menu_ID+"&sid="+School_ID+"&lid=" +
SchoolLevelId+"&mealid="+Meal_groupid;
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url",""+URL2);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity);
JSONObject json5 = new JSONObject(_response);
status = json5.getString("status");
if (status.equals("1")) {
JSONArray school5 = json5.getJSONArray("data");
}
}
else {
}
SelectMenuAPI2="";
SelectMenuAPI2 = Utils.SchoolVacation+mVal9;
// clearData();
URL3 = SelectMenuAPI2;
URL4 = URL3.replace(" ", "%20");
Log.i("url",""+URL4);
JSONObject json2 = new JSONObject(_response);
status = json2.getString("status");
if (status.equals("1")) {
if (Vacation_Date.contains(mydate)) {
message = "holiday";
JSONObject json4 = new JSONObject(str2);
status = json4.getString("status");
if (status.equals("1")) {
school = json4.getJSONArray("data");
for (int k = 0; k < school.length(); k++) {
JSONObject jb = (JSONObject) school .getJSONObject(k);
Vacation_ID.add((long) k);
String[] mVal = new String[school.length()];
if(school.getJSONObject(k).getString("date").equals(mydate))
{
mVal[k] = school.getJSONObject(k).getString("title");
mVal3 = mVal[k];
}
}
}
} else {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
if (object.getString("Schedule").equals("weekly")) {
if (object.getString("day").equals(Todayday)) {
Category_ID.add((long) i);
school_name
.add(object.getString("school_name"));
dish_ID.add(object.getString("dish_id"));
dish_name.add(object.getString("dish_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
count = count + 1;
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString("menu_title");
message = "weekly";
mVal2 = mVal[0];
}
}
if(dish_name != null &&
!dish_name.isEmpty())
{
message = "weekly";
}
else {
message = "error";
}
}
else {
message = "error";
}
}
}
}
else {
message = "error";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.e01:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e02:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e03:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e04:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e05:
listCategory.setVisibility(View.GONE);
// do stuff;
new getDataTask().execute();
break;
}
}
}
You are calling asynctask twice and that is making all parts twice, I mean you are cleaning twice before filling and fill arrays twice. You should control your async task for do not execute before last one finished.
1-Create a boolean value
2-Put condition on onClicks:
if(yourBoolean){
new getDataTask().execute();}
3- in your asyncTask's onPreExecute make yourBoolean=false and onPostExecute make yourBoolean=true again.
Try this..
Just remove the below line and try it..
listCategory.invalidateViews();
because
ListView.invalidateViews() is used to tell the ListView to invalidate all its child item views (redraw them). Note that there not need to be an equal number of views than items. That's because a ListView recycles its item views and moves them around the screen in a smart way while you scroll.
so i have been at it for hours and its 4:07 AM now i have to sleep, so i hope someone can help me.
I have an ArrayList of ImageResults objects the class of which is defined as:
public class ImageResults {
String _title, _country, _thumbnailURL, _imageURL;
public ImageResults(String title, String country, String thumbnailURL, String imageURL)
{
_title = title;
_country = country;
_thumbnailURL = thumbnailURL;
_imageURL = imageURL;
}
public String getTitle()
{
return _title;
}
public String getCountry()
{
return _country;
}
public String getThumbnailURL()
{
return _thumbnailURL;
}
public String getImageURL()
{
return _imageURL;
}
}
Now in order to use https://github.com/thest1/LazyList i have to retrieve the thumbnail urls from my arraylist of type imageresults and place them in an array like im doing here
private void populateListBox()
{
String[] imgLst = new String[imagesList.size()];
for(int i = 0; i < imagesList.size();i++)
{
imgLst[i] = (imagesList.get(i)._thumbnailURL);
// Toast t = Toast.makeText(this,imgLst[0] , Toast.LENGTH_SHORT);
// t.show();
}
adapter=new LazyAdapter(this, imgLst);
imageListView.setAdapter(adapter);
}
now the thing is the way it is above is not working but if i take the link individually as follows it works which is the default way the links are organized in the original project
private void populateListBox()
{
String[] imgLst={
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-AU1182456710.jpg&w=300"};
adapter=new LazyAdapter(this, imgLst);
imageListView.setAdapter(adapter);
}
this is how links are organized in the original project, and yest i am 100% sure that both methods are returning the same string just in different ways, one is fetching it from an object in an arraylist and the other im explicitly declaring it.
private String[] mStrings={
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-AU1182456710.jpg&w=300",
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-CA1182456710.jpg&w=300",
"http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
"http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg",
"http://a1.twimg.com/profile_images/97470808/icon_normal.png",
"http://a3.twimg.com/profile_images/511790713/AG.png",
"http://a3.twimg.com/profile_images/956404323/androinica-avatar_normal.png",
"http://a1.twimg.com/profile_images/909231146/Android_Biz_Man_normal.png",
"http://a3.twimg.com/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
"http://a1.twimg.com/profile_images/349012784/android_logo_small_normal.jpg"};
main activity class
public class BngPaperActivity extends Activity {
ListView imageListView;
Spinner countrySpinner;
String selectedMonth;
String selectedYear;
LazyAdapter adapter;
ProgressDialog progress;
Dialog date;
getResult getRes;
String ResultsString;
ArrayList<String> monthList = new ArrayList<String>();
ArrayList<ImageResults> imagesList = new ArrayList<ImageResults>();
String dateText;
TextView selectedDateView;
static final int MONTHYEARDATESELECTOR_ID = 3;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = new ProgressDialog(BngPaperActivity.this);
monthList.add("January"); monthList.add("February"); monthList.add("March"); monthList.add("April");
monthList.add("May"); monthList.add("June"); monthList.add("July"); monthList.add("August");
monthList.add("September"); monthList.add("October"); monthList.add("November"); monthList.add("December");
imageListView = (ListView) this.findViewById(R.id.imagesListView);
countrySpinner = (Spinner) this.findViewById(R.id.countrySpinner);
selectedDateView = (TextView) this.findViewById(R.id.selectedDateView);
Button monthYearButton = (Button) this.findViewById(R.id.monthyearBTN);
// set up a listener for when the button is pressed
monthYearButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// call the internal showDialog method using the predefined ID
showDialog(MONTHYEARDATESELECTOR_ID);
}
});
}
private DateSlider.OnDateSetListener mMonthYearSetListener =
new DateSlider.OnDateSetListener() {
public void onDateSet(DateSlider view, Calendar selectedDate) {
// update the dateText view with the corresponding date
dateText = (String.format("%tB %tY", selectedDate, selectedDate));
selectedDateView.setText(dateText);
try {
selectedMonth = monthList.indexOf(String.format("%tB", selectedDate)) + 1 +"";
selectedYear = String.format("%tY", selectedDate);
progress.setMessage("Fetching Images... \nPress Back Button To Cancel");
progress.setCancelable(true);
getRes = new getResult(progress,view);
getRes.execute();
try {
ResultsString = getRes.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parseResults(ResultsString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private void parseResults(String result)
{
Scanner scan = new Scanner(result);
String current = scan.nextLine();
String title = "";
String country = "";
String thumbURL = "";
String imageURL = "";
while(!current.equals("End of file"))
{
if(current.equals("Begin Thumb"))
{
current = scan.nextLine();
title = current.substring(current.indexOf(":")+1);
current = scan.nextLine();
country = current.substring(current.indexOf(":")+1);
current = scan.nextLine();
thumbURL = current.substring(current.indexOf(":")+1);
imageURL = thumbURL.replace("300", "900");
current = scan.nextLine();
}
if(current.equals("End Thumb"))
{
imagesList.add(new ImageResults(title,country,thumbURL,imageURL));
}
current = scan.nextLine();
}
populateListBox();
}
private void populateListBox()
{
//this is not working, i would like this one to work
String[] imgLst = new String[imagesList.size()];
for(int i = 0; i < imagesList.size();i++)
{
imgLst[i] = (imagesList.get(i)._thumbnailURL);
// Toast t = Toast.makeText(this,imgLst[0] , Toast.LENGTH_SHORT);
// t.show();
}
//-----------------------------------
/* This is working
String[] imgLst={
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-AU1182456710.jpg&w=300"};
*/
adapter=new LazyAdapter(this, imgLst);
imageListView.setAdapter(adapter);
}
#Override
protected Dialog onCreateDialog(int id) {
// this method is called after invoking 'showDialog' for the first time
// here we initiate the corresponding DateSlideSelector and return the dialog to its caller
final Calendar c = Calendar.getInstance();
final Calendar minDate = Calendar.getInstance();
minDate.set(Calendar.YEAR, 2009);
minDate.set(Calendar.MONTH, Calendar.JUNE);
final Calendar maxDate = Calendar.getInstance();
maxDate.add(Calendar.DATE, 0);
switch (id) {
case MONTHYEARDATESELECTOR_ID:
return new MonthYearDateSlider(this,mMonthYearSetListener,c,minDate,maxDate);
}
return null;
}
private class getResult extends AsyncTask<String, String, String> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog progress;
DateSlider view;
public getResult(ProgressDialog progress, DateSlider view)
{
this.progress = progress;
this.view = view;
}
protected void onPreExecute() {
this.view.dismiss();
this.progress.show();
}
#Override
protected String doInBackground(String... urls) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet("http://devleb.com/BngPaper/BngPaperWebService.php?thumbnail=Yes&year="+selectedYear+"&month="+ selectedMonth));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
//Dialog.dismiss();
progress.dismiss();
return responseString;
}
protected void onPostExecute(Void unused) {
this.progress.dismiss();
if (Error != null) {
Toast.makeText(BngPaperActivity.this, Error, Toast.LENGTH_LONG).show();
}
}
}
}
The following doesn't work?
private void populateListBox()
{
adapter=new LazyAdapter(this, mStrings);
imageListView.setAdapter(adapter);
}
Like in the example given in the lazylist project.