Get id of an ImageView in Scrollview in Android - android

How can I get the id of an element that has been clicked, if this element is found in a scrollView? In my case I have 4 photos (ImageViews) and if I click on one of them, I want to get its id (already set with ImageView.setId(int) ). Here is my code:
package scroll.s;
import android.app.Activity;
import android.os.Bundle;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ScrollsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int layoutId = 0;
RelativeLayout main = new RelativeLayout(this);
RelativeLayout.LayoutParams mainParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
main.setId(layoutId);
layoutId++;
TextView past = new TextView (this);
RelativeLayout.LayoutParams pastParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
past.setId(layoutId);
layoutId++;
past.setText("Past: ");
pastParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
main.addView(past, pastParams);
final HorizontalScrollView hsv = new HorizontalScrollView(this);
hsv.setId(layoutId);
layoutId++;
hsv.setHorizontalScrollBarEnabled(false);
mainParams.addRule(RelativeLayout.BELOW, 1);
main.addView(hsv, mainParams);
final RelativeLayout relative1 = new RelativeLayout(this);
relative1.setId(layoutId);
layoutId++;
hsv.addView(relative1);
for (int i=0; i<4; i++) {
ImageView current = new ImageView(this);
current.setBackgroundDrawable(getResources().getDrawable(R.drawable.example));
current.setId(layoutId);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, (layoutId-1) );
params.leftMargin=10;
relative1.addView(current, params);
layoutId++;
}
for (int i=0; i<4; i++) {
TextView currentText = new TextView(this);
currentText.setText("random text");
currentText.setId(layoutId);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, (layoutId-4) );
params.addRule(RelativeLayout.ALIGN_LEFT, (layoutId-4) );
params.topMargin=5;
relative1.addView(currentText, params);
layoutId++;
}
this.setContentView(main);
}
}
Here is what I achieve with this code :
I get the ERROR/AndroidRuntime(2258): android.content.res.Resources$NotFoundException: String resource ID #0x4
when I put the following code:
current.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), current.getId(), Toast.LENGTH_SHORT).show();
}
});

Change it to:
current.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), String.valueOf(v.getId()), Toast.LENGTH_SHORT).show();
}
});

the second parameter of the method makeText() , is a String , not an Int ( current.getId() ) , so you should convert it to a String like this :
current.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),""+v.getId(), Toast.LENGTH_SHORT).show();
}
});

Related

Not able to capture HTML from the browser for Android

I am trying to capture HTML code response from browser. I have created a browser and trying to capture HTML content and print in logcat.
I am getting following error message in logcat:
01-28 13:36:18.914 4079-4079/com.aseelarbazanny.myweb D/PocketMagic: onPageFinished
01-28 13:36:18.954 4079-4079/com.aseelarbazanny.myweb I/chromium: [INFO:CONSOLE(1)] "Uncaught TypeError: Object [object Object] has no method 'showHTML'", source: http://www.pocketmagic.net/ (1)
Here is the code I have done so far:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class AndroidBrowserGUI extends Activity implements View.OnClickListener {
// constants
final static String LOG_TAG = "PocketMagic";
final static int idTopLayout = Menu.FIRST + 100,
idBack = Menu.FIRST + 101,
idBotLayout = Menu.FIRST + 102,
idAddr = Menu.FIRST + 103,
idButBack = Menu.FIRST + 104,
idButFwd = Menu.FIRST + 105,
idButReload = Menu.FIRST + 106,
idButStop = Menu.FIRST + 107,
idButGo = Menu.FIRST + 108;
// interface controls
String m_szPage = "http://www.pocketmagic.net";
int m_nHTMLSize = 0;
WebView m_web;
EditText m_etAddr;
TextView m_tv;
Button m_bButBack, m_bButFwd, m_bButReload, m_bButStop, m_bButGo;
#Override
#SuppressLint("JavascriptInterface")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hide titlebar
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Create our top content holder
RelativeLayout global_panel = new RelativeLayout (this);
global_panel.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT));
global_panel.setGravity(Gravity.FILL);
global_panel.setBackgroundDrawable(getResources().getDrawable( R.drawable.back));
// +++++++++++++ TOP COMPONENT: the header
RelativeLayout ibMenu = new RelativeLayout(this);
ibMenu.setId(idTopLayout);
ibMenu.setBackgroundDrawable(getResources().getDrawable(R.drawable.line));
int ibMenuPadding = (int) 6;
ibMenu.setPadding(ibMenuPadding,ibMenuPadding,ibMenuPadding,ibMenuPadding);
RelativeLayout.LayoutParams topParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
topParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
global_panel.addView(ibMenu,topParams);
//
int nTextH = 12;
// go button
m_bButGo = new Button(this);
m_bButGo.setId(idButGo);
m_bButGo.setOnClickListener((View.OnClickListener) this);
m_bButGo.setText("Go");
m_bButGo.setTextSize(nTextH);
m_bButGo.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb5 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb5.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lpb5.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenu.addView(m_bButGo, lpb5);
// address field
m_etAddr = new EditText(this);
m_etAddr.setId(idAddr);
m_etAddr.setText(m_szPage);
nTextH = 12;
m_etAddr.setTextSize(nTextH);
m_etAddr.setTypeface(Typeface.create("arial", Typeface.NORMAL));
RelativeLayout.LayoutParams lpbEdit =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpbEdit.addRule(RelativeLayout.RIGHT_OF, idButGo);
lpbEdit.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenu.addView(m_etAddr, lpbEdit);
// +++++++++++++ BOTTOM COMPONENT: the footer
RelativeLayout ibMenuBot = new RelativeLayout(this);
ibMenuBot.setId(idBotLayout);
ibMenuBot.setBackgroundDrawable(getResources().getDrawable(R.drawable.line));
ibMenuBot.setPadding(ibMenuPadding,ibMenuPadding,ibMenuPadding,ibMenuPadding);
RelativeLayout.LayoutParams botParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
botParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
global_panel.addView(ibMenuBot,botParams);
m_bButBack = new Button(this);
m_bButBack.setId(idButBack);
m_bButBack.setOnClickListener((View.OnClickListener) this);
m_bButBack.setText("Back");
m_bButBack.setTextSize(nTextH);
m_bButBack.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb1 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lpb1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenuBot.addView(m_bButBack, lpb1);
// fwd button
m_bButFwd = new Button(this);
m_bButFwd.setId(idButFwd);
m_bButFwd.setOnClickListener((View.OnClickListener) this);
m_bButFwd.setText("Fwd");
m_bButFwd.setTextSize(nTextH);
m_bButFwd.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb2 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb2.addRule(RelativeLayout.RIGHT_OF, idButBack);
lpb2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenuBot.addView(m_bButFwd, lpb2);
// reload button
m_bButReload = new Button(this);
m_bButReload.setId(idButReload);
m_bButReload.setOnClickListener((View.OnClickListener) this);
m_bButReload.setText("Rld");
m_bButReload.setTextSize(nTextH);
m_bButReload.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb3 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb3.addRule(RelativeLayout.RIGHT_OF, idButFwd);
lpb3.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenuBot.addView(m_bButReload, lpb3);
// stop button
m_bButStop = new Button(this);
m_bButStop.setId(idButStop);
m_bButStop.setOnClickListener((View.OnClickListener) this);
m_bButStop.setText("Stop");
m_bButStop.setTextSize(nTextH);
m_bButStop.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpb4 =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpb4.addRule(RelativeLayout.RIGHT_OF, idButReload);
lpb4.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ibMenuBot.addView(m_bButStop, lpb4);
// status
m_tv = new TextView(this);
m_tv.setText("Status");
m_tv.setTextColor(Color.rgb(255,255,255));
m_tv.setTextSize(nTextH);
m_tv.setTypeface(Typeface.create("arial", Typeface.BOLD));
RelativeLayout.LayoutParams lpcTV = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpcTV.addRule(RelativeLayout.RIGHT_OF, idButStop);
lpcTV.addRule(RelativeLayout.CENTER_VERTICAL);
ibMenuBot.addView(m_tv, lpcTV);
// +++++++++++++ MIDDLE COMPONENT: only a webview control
m_web = new WebView(this);
m_web.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT));
RelativeLayout.LayoutParams midParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
midParams.addRule(RelativeLayout.ABOVE,ibMenuBot.getId());
midParams.addRule(RelativeLayout.BELOW,ibMenu.getId());
global_panel.addView(m_web,midParams );
// Configure our webview object
m_web.getSettings().setJavaScriptEnabled(true);
m_web.setWebViewClient(new MyWebViewClient());
// set starting page
if (m_szPage != null) m_web.loadUrl(m_szPage);
// set java script used to get the HTML code
m_web.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");
// Interface READY
setContentView(global_panel);
}
// Used with Webview, to get the HTML code
class JavaScriptInterface{
public void showHTML(String html) {
m_nHTMLSize = 0;
if (html !=null) {
//int i = html.lastIndexOf(""); //search for something in the text
m_nHTMLSize = html.length();
Log.d(LOG_TAG, "HTML content is: "+html+"\nSize:"+m_nHTMLSize+" bytes");
}
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(LOG_TAG, "onPageStarted");
m_tv.setText("Loading page...");
//stop button is enabled only when pages are loading
m_bButStop.setEnabled(true);
}
#Override
public void onPageFinished(WebView view, String url) {
Log.d(LOG_TAG, "onPageFinished");
m_tv.setText("Ready");
//stop button is disabled when pages are already loaded
m_bButStop.setEnabled(false);
// This call inject JavaScript into the page which just finished loading.
m_web.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
// adjust prev/next buttons, only if history is available
m_bButBack.setEnabled(m_web.canGoBack());
m_bButFwd.setEnabled(m_web.canGoForward());
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
int id = arg0.getId();
// If cancel is pressed, close our app
if (id == idBack) finish();
if (id == idButGo) {
m_szPage = m_etAddr.getText().toString();
Log.d(LOG_TAG, "Go for page:"+m_szPage);
if (m_szPage != null) m_web.loadUrl(m_szPage);
}
if (id == idButBack) {
Log.d(LOG_TAG, "Go back");
m_web.goBack();
}
if (id == idButFwd) {
Log.d(LOG_TAG, "Go forward");
m_web.goForward();
}
if (id == idButReload) {
Log.d(LOG_TAG, "Reload page");
m_web.reload();
}
if (id == idButStop) {
Log.d(LOG_TAG, "Stop loading page");
m_web.stopLoading();
}
}
}
Starting from API level JELLY_BEAN_MR1 and above, only methods explicitly marked with the #JavascriptInterface annotation are available to the Javascript code.
You just need to add this above your showHTML method e.g:
class JavaScriptInterface{
#JavascriptInterface
public void showHTML(String html) {
m_nHTMLSize = 0;
if (html !=null) {
//int i = html.lastIndexOf(""); //search for something in the text
m_nHTMLSize = html.length();
Log.d(LOG_TAG, "HTML content is: "+html+"\nSize:"+m_nHTMLSize+" bytes");
}
}
}
Also need to remove window from you JS call:
m_web.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
to
m_web.loadUrl("javascript:HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");

get value from edit text within a loop

I have a question, as I can get all the data that has been inserted into the edit text? the edit text is on a loop, I need a way to get those values ​​and work with them, try using an array but I get errors. could help me? any idea? Help!
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText count = (EditText) findViewById(R.id.count);
final Button generate = (Button) findViewById(R.id.generate);
final LinearLayout container = (LinearLayout) findViewById(R.id.container);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberOfControlsToGenerate = 0;
try {
numberOfControlsToGenerate = Integer.parseInt(count.getText().toString().trim());
} catch (NumberFormatException e) {
Log.e(TAG, e.getMessage(), e);
}
if (numberOfControlsToGenerate > 0) {
if (container.getChildCount() > 0) {
container.removeAllViews();
}
for (int counter = 0; counter < numberOfControlsToGenerate; counter++) {
addEditText(container);
}
}
}
});
}
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
container.addView(editTextToAdd);
}
}
You can create multiple edittext by using array.
public class MainActivity extends Activity{
EditText[] sample_et;
int numberOfControlsToGenerate = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
LinearLayout root_layout = (LinearLayout)findViewById(R.id.root);
sample_et = new EditText[numberOfControlsToGenerate];
//numberOfControlsToGenerate is decleres statically you can get the count from edit text
for(int i = 0; i < count; i++ ){
sample_et[i] = new EditText(this);
root_layout.addView(sample_et[i]);
}
}
}
Add setTag when you create dynamic EditText
add line in addEditText(LinearLayout container) method
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
editTextToAdd.setTag(editTextToAdd); //Add this Line
container.addView(editTextToAdd);
}
Write code onClick listener on any Button
getvalue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < container.getChildCount(); i++) {
if(container.getChildAt(i) instanceof EditText) {
EditText et = (EditText) container.getChildAt(i).getTag();
if(et != null) {
Log.i("<Tag Name>", et.getText().toString());
}
}
}
}
});

making press effect for button in android

i've created an android application which creates 50 button dynamically,which works perfectly, but the problem is when i put some background color for these buttons dynamically the press effect of the buttons is being lost
can anyone please tell me some solution for retaining the press effect of the button click
my code is as given below
my Android Platform is 2.3.3
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
public class MyMain extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mymain);
createCalender();
}
public void createCalender()
{
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1.0f);
param.setMargins(10, 10, 10, 10);
LinearLayout rowLayout=null;
Button[][] buttons = new Button[10][5];
int count=51;
int tab=1;
for (int i = 0; i<10; i++)
{
if(count%5==1)
{
rowLayout = new LinearLayout(this);
rowLayout.setBackgroundColor(Color.BLACK);
rowLayout.setWeightSum(5);
layoutVertical.addView(rowLayout,param);
count=count-5;
}
for(int j=0;j<5;j++)
{
buttons[i][j]=new Button(this);
buttons[i][j].setText(""+tab);
buttons[i][j].setHeight(55);
buttons[i][j].setWidth(80);
buttons[i][j].setTextColor(Color.BLACK);
buttons[i][j].setBackgroundColor(Color.GREEN);
tab++;
rowLayout.addView(buttons[i][j],param);
}
}
}
}
After buttons[i][j].setBackgroundColor(Color.GREEN);
buttons[i][j].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundColor(Color.GRAY); // Choose whichever color
new Handler().postDelayed(new Runnable() {
public void run() {
v.setBackgroundColor(Color.GREEN);
// Button Click Code Here
}
}, 100L); // Change this value to whatever is suitable
}
});

Android ObserveableScrollView to load more (loading issue)

I am fetching information from the website in JSON Format and displaying that info into my app using AsynTask. The Problem is that on On First time my Progress dialog shows well and hide after loading contents into app. But When i use Scroll-view to load more then progress dialog appears and hide after loading immediately at the same time progress dialog opens again and not hiding and Scroll-View loads data one more time in the background.I want only one time to load data after each using Scroll-View to load more. Progress Dialog is not hiding and It keeps running my app. I am struck at this point.
Basically i noticed that My Scroll-View indicator collide two times on the bottom due to this scroll-View trigger two times. How can i stop it and restrict this only one time after each scrolling.
And one more thing wanna share that everything is working awesome in Froyo 2.2 and not working in 2.3 to 4.2. Kindly help me on this. Thanks in advance.
Below is my code.
package com.example.lmf;
import java.net.URLEncoder;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.lmf.ObservableScrollView.ScrollViewListener;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
public class searchClassified extends Activity implements ScrollViewListener
{
ObservableScrollView scrollView;
ProgressDialog _progressDialog;
int page_no = 1;
String k = "";
final static String URL = "http://www.lmf.com.pk/admin/json.php?YOUR URL OF JSON";
final getInternetData obj = new getInternetData();
public ImageLoader imageLoader = null;
Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_classified);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
scrollView = (ObservableScrollView) findViewById(R.id.my_scroll);
scrollView.setScrollViewListener(this);
imageLoader = new ImageLoader(this);
String s = getIntent().getExtras().getString("query")!= "" ? getIntent().getExtras().getString("query") : "";
EditText et = (EditText) findViewById(R.id.query);
et.setText(s);
k = "all="+URLEncoder.encode(s);
//showProgress(context);
new getBackgroundData().execute();
}
public void onScrollEnded(ObservableScrollView scrollView, int x, int y,
int oldx, int oldy) {
// TODO Auto-generated method stub
page_no = page_no + 1;
k = k+"&page_no="+page_no;
//showProgress(context);
getBackgroundData d1 = new getBackgroundData();
d1.execute();
if(d1.getStatus()==AsyncTask.Status.FINISHED) {
d1 = null;
_progressDialog.dismiss();
}
}
public void searchAds(View v)
{
EditText query = (EditText) findViewById(R.id.query);
String q = query.getText().toString();
if(q == "" || q == "search")
{
Dialog d = new Dialog(this);
d.setTitle("Enter Valid Search Parameter");
d.show();
}
else
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Intent i = new Intent(searchClassified.this,com.example.lmf.searchClassified.class);
i.putExtra("query", ""+q+"");
startActivity(i);
}
}
public void showProgress(Context c)
{
_progressDialog = ProgressDialog.show(
c,
"Please wait",
"Performing task..."
);
}
public void hideProgress()
{
_progressDialog.dismiss();
}
//////////// Async Class
private class getBackgroundData extends AsyncTask<Void, Integer, JSONArray>
{
protected void onPreExecute()
{
_progressDialog = new ProgressDialog(context);
_progressDialog.setMessage("Loading...");
_progressDialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
try
{
JSONArray array = obj.getDATA(k,URL);
return array;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray array)
{
LinearLayout sv = (LinearLayout) findViewById(R.id.data);
try
{
for (int i = 0; i <array.length(); i++) {
JSONObject row = array.getJSONObject(i);
//// TextView Creation start here /////////
TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
tv.setText(row.getString("post_title"));
tv.setTextColor(Color.BLACK);
tv.setTextSize(14);
tv.setPadding(8, 6, 0, 12);
tv.setFocusable(true);
tv.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
//// TextView Creating Ends here /////////
//// Horizontal Line Creating here /////////
View v = new View(searchClassified.this);
LinearLayout.LayoutParams viewLp = new LayoutParams(LayoutParams.MATCH_PARENT, 1);
viewLp.setMargins(0, 4, 0, 4);
v.setLayoutParams(viewLp);
v.setBackgroundColor(Color.LTGRAY);
//// Horizontal Line Creating Ends here /////////
//// Image Creating Starts from here /////////
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(3, 0, 15, 8);
lp.width = 70;
lp.height = 80;
ImageView imageView = new ImageView(searchClassified.this);
String[] parts = row.getString("post_img").split("/");
int last_index = parts.length - 1;
String image_name = "thumb_"+parts[last_index];
String str = "";
for(int j=0; j<last_index; j++)
{
str += parts[j]+"/";
}
String path = "http://www.lmf.com.pk/"+str+image_name;
imageLoader.DisplayImage(path, imageView);
//// Image Creating Ends here /////////
// Creating LinearLAyout /////////
LinearLayout l1 = new LinearLayout(searchClassified.this);
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setHapticFeedbackEnabled(true);
l1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
l1.setId(obj.convertStrtoInt(row.getString("post_id")));
l1.setHapticFeedbackEnabled(true);
l1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(searchClassified.this,com.example.lmf.adsDetail.class);
i.putExtra("id", v.getId());
startActivity(i);
}
});
l1.addView(imageView, lp);
l1.addView(tv);
sv.addView(l1);
sv.addView(v);
}
_progressDialog.hide();
_progressDialog.dismiss();
_progressDialog = null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
/////////// Ends Here
public boolean onCreateOptionsMenu(Menu menu)
{
MenuItem item = menu.add ("Quit");
item.setOnMenuItemClickListener (new OnMenuItemClickListener()
{
public boolean onMenuItemClick (MenuItem item)
{
//clearArray();
finish();
return true;
}
});
return true;
}
}
I have Solved this issue and want to share with the future readers. I made a switch and add cases now the new Scroll-View trigger can not run until the previous data will not complete loads.
Here is the final code and hope will help you friends. Thanks
package com.example.lmf;
import java.net.URLEncoder;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.lmf.ObservableScrollView.ScrollViewListener;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
public class searchClassified extends Activity implements ScrollViewListener
{
ObservableScrollView scrollView;
ProgressDialog _progressDialog;
int page_no = 1;
String k = "";
final static String URL = "Your URL HERE For Getting JSON";
final getInternetData obj = new getInternetData();
public ImageLoader imageLoader = null;
Context context = this;
int num = 1;
private static final int SPLASH_DURATION = 3000; // 3 seconds
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_classified);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
scrollView = (ObservableScrollView) findViewById(R.id.my_scroll);
scrollView.setScrollViewListener(this);
imageLoader = new ImageLoader(this);
String s = getIntent().getExtras().getString("query")!= "" ? getIntent().getExtras().getString("query") : "";
EditText et = (EditText) findViewById(R.id.query);
et.setText(s);
k = "all="+URLEncoder.encode(s);
showProgress();
new getBackgroundData().execute();
}
public void onScrollEnded(ObservableScrollView scrollView, int x, int y, int oldx, int oldy)
{
// TODO Auto-generated method stub
page_no = page_no + 1;
k = k+"&page_no="+page_no;
switch(num)
{
case 1:
showProgress();
new getBackgroundData().execute();
num = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
num = 1;
}
}, SPLASH_DURATION);
break;
case 0:
num = 0;
break;
}
}
public void searchAds(View v)
{
EditText query = (EditText) findViewById(R.id.query);
String q = query.getText().toString();
if(q == "" || q == "search")
{
Dialog d = new Dialog(this);
d.setTitle("Enter Valid Search Parameter");
d.show();
}
else
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Intent i = new Intent(searchClassified.this,com.example.lmf.searchClassified.class);
i.putExtra("query", ""+q+"");
startActivity(i);
}
}
public void showProgress()
{
_progressDialog = new ProgressDialog(context);
_progressDialog.setMessage("Loading...");
_progressDialog.show();
}
public void hideProgress()
{
_progressDialog.dismiss();
}
//////////// Async Class
private class getBackgroundData extends AsyncTask<Void, Integer, JSONArray>
{
#Override
protected JSONArray doInBackground(Void... params)
{
try
{
JSONArray array = obj.getDATA(k,URL);
return array;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray array)
{
LinearLayout sv = (LinearLayout) findViewById(R.id.data);
try
{
for (int i = 0; i <array.length(); i++) {
JSONObject row = array.getJSONObject(i);
//// TextView Creation start here /////////
TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
tv.setText(row.getString("post_title"));
tv.setTextColor(Color.BLACK);
tv.setTextSize(14);
tv.setPadding(8, 6, 0, 12);
tv.setWidth(350);
tv.setHeight(100);
tv.setFocusable(true);
LinearLayout.LayoutParams tvPar = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//tvPar.weight = 2;
tv.setLayoutParams(tvPar);
//// TextView Creating Ends here /////////
//// Horizontal Line Creating here /////////
View v = new View(searchClassified.this);
LinearLayout.LayoutParams viewLp = new LayoutParams(LayoutParams.MATCH_PARENT, 1);
viewLp.setMargins(0, 4, 0, 4);
v.setLayoutParams(viewLp);
v.setBackgroundColor(Color.LTGRAY);
//// Horizontal Line Creating Ends here /////////
//// More Detail Icon Ends /////////////////////
ImageView more_info_icon = new ImageView(searchClassified.this);
//setting image resource
more_info_icon.setImageResource(R.drawable.arrow);
//setting image position
LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//par.weight = 1;
more_info_icon.setLayoutParams(par);
more_info_icon.getLayoutParams().height = 30;
more_info_icon.getLayoutParams().width = 30;
more_info_icon.setPadding(0, 14, 0, 0);
/// More Detail Icon Ends Here /////////////////////
//// Image Creating Starts from here /////////
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,4);
lp.weight = 1;
lp.setMargins(3, 0, 15, 8);
lp.width = 70;
lp.height = 80;
ImageView imageView = new ImageView(searchClassified.this);
String[] parts = row.getString("post_img").split("/");
int last_index = parts.length - 1;
String image_name = "thumb_"+parts[last_index];
String str = "";
for(int j=0; j<last_index; j++)
{
str += parts[j]+"/";
}
String path = "http://www.lmf.com.pk/"+str+image_name;
imageLoader.DisplayImage(path, imageView);
//// Image Creating Ends here /////////
// Creating LinearLAyout /////////
final LinearLayout l1 = new LinearLayout(searchClassified.this);
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setHapticFeedbackEnabled(true);
LinearLayout.LayoutParams LParam = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LParam.weight = 4;
l1.setLayoutParams(LParam);
l1.setId(obj.convertStrtoInt(row.getString("post_id")));
l1.setHapticFeedbackEnabled(true);
l1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
l1.setBackgroundColor(Color.GREEN);
//l1.setBackgroundColor(Color.WHITE);
Intent i = new Intent(searchClassified.this,com.example.lmf.adsDetail.class);
i.putExtra("id", v.getId());
startActivity(i);
}
});
l1.addView(imageView, lp);
l1.addView(tv);
l1.addView(more_info_icon);
sv.addView(l1);
sv.addView(v);
}
hideProgress();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
/////////// Ends Here
public boolean onCreateOptionsMenu(Menu menu)
{
MenuItem item = menu.add ("Quit");
item.setOnMenuItemClickListener (new OnMenuItemClickListener()
{
public boolean onMenuItemClick (MenuItem item)
{
//clearArray();
finish();
return true;
}
});
return true;
}
}

On click Listener called twice

I know this is easy but i m just not able to debug it.
I am dynamically creating 3 LinearLayouts and adding them to a scroll View . I am adding a Button "ins" to the top of 3 linearlayout.
The problem is that on clicking the ins Button , its on clicklistener is being called 3 times .
code:
package com.integrated.mpr;
import android.app.Activity;
import android.app.Dialog;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class Page1 extends Activity implements OnClickListener{
static int pos = new Choose().n;
static String partname;
int i;
int[][] id = new int[pos][5];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int p =0;
for(int i =0;i<3;i++){
for(int j =0;j<5;j++){
p++;
}
}
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
int resid = getResources().getIdentifier("background", "drawable", getPackageName());
ll.setBackgroundResource(resid);
Button ins = new Button(this);
ins.setText("Instructions");
ins.setOnClickListener(this);
ins.setId(5000);
ll.addView(ins);
for(i =0;i<3;i++){
LinearLayout llay = new LinearLayout(this);
llay.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
tv.setText("enter the " +(i+1)+" position name");
EditText et = new EditText(this);
et.setId(id[i][0]);
Button starta = new Button(this);
starta.setText("Record 1");
starta.setId(id[i][1]);
starta.setOnClickListener(this);
Button startb = new Button(this);
startb.setText("Record 2");
startb.setId(id[i][2]);
startb.setOnClickListener(this);
Button startc = new Button(this);
startc.setText("Record 3");
startc.setId(id[i][3]);
startc.setOnClickListener(this);
Button stop = new Button(this);
stop.setText("Submit");
stop.setId(id[i][4]);
stop.setOnClickListener(this);
TextView tv1 = new TextView(this);
tv1.setVisibility(llay.INVISIBLE);
llay.addView(tv);
llay.addView(et);
llay.addView(starta);
llay.addView(startb);
llay.addView(startc);
llay.addView(stop);
llay.addView(tv1);
ll.addView(llay);
}
Button bcon = new Button(this);
bcon.setText("Continue");
bcon.setId(10000);
bcon.setOnClickListener(this);
ll.addView(bcon);
sv.addView(ll);
this.setContentView(sv);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==5000){
Log.d("ins", "called");
Context mContext = Page1.this;
Dialog dialog = new Dialog(mContext);
dialog.setTitle("Instructions");
dialog.setContentView(R.layout.instructiondialog);
dialog.show();
}
}
}
}
I know definitely , there is some problem in the code of OnCreate but what it is ? Help please
Can anyone further explain how to set the button aligned o the right of screen , that is how to set its layout gravity?
I am not sure about what exactly you want to achieve.but you can set the flag.if flag value is 1 then only process onClick else not.
Below snippet will help you.
Yes but you will have to somehow reset that flag to 1.
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(v.getId()==5000)
{
if(flag)
{
Log.d("ins", "called");
Context mContext = Page1.this;
Dialog dialog = new Dialog(mContext);
dialog.setTitle("Instructions");
dialog.setContentView(R.layout.instructiondialog);
dialog.show();
}
flag=0;
}
}
You can also call button click event like this
Button ins = new Button(this);
ins.setText("Instructions");
ins.setOnClickListener(this);
ins.setId(5000);
ins.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
Context mContext = Page1.this;
Dialog dialog = new Dialog(mContext);
dialog.setTitle("Instructions");
dialog.setContentView(R.layout.instructiondialog);
dialog.show();
}
});

Categories

Resources