i need to achieve horizontal scrolling of pages while swiping
i have loaded data in the order of json ,inside the textview and webview
i have used viewpager for achieving that operation
im receiving the error as shown in log cat
i have used removeView() method ,error is showing up again
Kindly Help me to solve this
Thanks in advance
My Code
package singlearticle;
import com.yslabs.yourstory.R;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
#SuppressLint("SetJavaScriptEnabled")
public class SingleArticle extends Activity {
String t = single.title;
String p = single.permalink;
String f = single.featured_img;
String a = single.author;
String d = single.date;
String articleComment = "article url" + p;
private WebView web1, fbCommentview;
ConnectionDetector checkConnection;
Boolean isInternetPresent = false;
ViewPager viewPage;
MyPagerAdapter mypageAdapter;
private ProgressDialog pDialog;
#SuppressWarnings("deprecation")
#SuppressLint({ "InflateParams", "SetJavaScriptEnabled", "HandlerLeak",
"NewApi" })
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.singlearticle);
viewPage = (ViewPager) findViewById(R.id.myviewpager);
mypageAdapter = new MyPagerAdapter();
viewPage.setAdapter(mypageAdapter);
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#f8f8f8")));
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ActionBar mActionBar = getActionBar();
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(SingleArticle.this);
View mCustomView = mInflater
.inflate(R.layout.customactionbar,null);
TextView mTitleTextView = (TextView) mCustomView
.findViewById(R.id.title_text);
Typeface fontt = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
mTitleTextView.setTypeface(fontt);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setLogo(R.drawable.backicon);
// getActionBar().setIcon(
// new
// ColorDrawable(getResources().getColor(android.R.color.transparent)));
pDialog = new ProgressDialog(SingleArticle.this);
pDialog.setMessage("Loading...");
pDialog.show();
pDialog.setCancelable(false);
final Handler h = new Handler() {
public void handleMessage(Message message) {
pDialog.dismiss();
}
};
h.sendMessageDelayed(new Message(), 500);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main2, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_refresh:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, t + "\n" + p);
sendIntent.setType("text/plain");
startActivity(sendIntent);
return true;
case android.R.id.home:
onBackPressed();
web1.loadUrl("");
web1.stopLoading();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
// progressBar.setVisibility(View.GONE);
}
}
// To handle "Back" key press event for WebView to go back to previous
// screen.
#SuppressWarnings("static-access")
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == event.KEYCODE_BACK) {
web1.loadUrl("");
web1.stopLoading();
finish();
}
return super.onKeyDown(keyCode, event);
}
private class MyPagerAdapter extends PagerAdapter {
int articleCount = 5;
#Override
public int getCount() {
// returns article count
return articleCount;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
// assigns object to view
return view == ((LinearLayout)obj);
}
#SuppressLint("NewApi")
#Override
public Object instantiateItem(ViewGroup container, int position) {
d = d.substring(0, d.length() - 3);
String c = single.content;
c = c.replace("src=\"//", "src=\"https://");
final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(c, ALLOWED_URI_CHARS);
String htmldata = "<!DOCTYPE html><html><style = text/css> img{width:100%!important;height:auto!important;} iframe{width:100sp;max-height:100sp;}a { color:#3366CC; text-decoration: none; } </style> <body style = 'line-height:25px;'>"
+ c + "</body></html>";
TextView titleTxt = (TextView) findViewById(R.id.singletitle);
titleTxt.setText(t);
// tt = titleTxt.getText().toString();
Typeface font = Typeface.createFromAsset(getAssets(),
"Helvetica Neue UltraLight.ttf");
Typeface font22 = Typeface.createFromAsset(getAssets(),
"helvetica-neue-regular-1361522098.ttf");
titleTxt.setTypeface(font);
titleTxt.setTypeface(font22);
titleTxt.setTypeface(null, Typeface.BOLD);
TextView authorTxt = (TextView) findViewById(R.id.singleauthor);
authorTxt.setText(a);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
authorTxt.setTypeface(font1);
TextView dateTxt = (TextView) findViewById(R.id.singledate);
dateTxt.setText(d);
Typeface font2 = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
dateTxt.setTypeface(font2);
TextView permalinkTxt = (TextView) findViewById(R.id.singleperlink);
permalinkTxt.setText(p);
permalinkTxt.setVisibility(View.GONE);
// pp = permalinkTxt.getText().toString();
// datep.setVisibility(View.GONE);
web1 = (WebView) findViewById(R.id.webView2);
web1.setWebViewClient(new myWebClient());
web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
web1.getSettings().setJavaScriptEnabled(true);
// web1.getSettings().setJavaScriptEnabled(true);
// web1.setInitialScale(65);
web1.getSettings().setDefaultFontSize(18);
web1.setWebChromeClient(new WebChromeClient());
web1.getSettings().setPluginState(PluginState.ON_DEMAND);
// web1.loadUrl("http://dev.skyle.co/fbSDK.php?data="+urlEncoded);
web1.loadData(htmldata, "text/html; charset=utf-8", null);
web1.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent in = new Intent(SingleArticle.this, webview.class);
webclass.webdata = url.toString();
startActivity(in);
return true;
}
});
fbCommentview = (WebView) findViewById(R.id.fbCommentview);
/*
* to check internet and show/hide facebook part
*/
checkConnection = new ConnectionDetector(getApplicationContext());
isInternetPresent = checkConnection.isConnectingToInternet();
if (isInternetPresent) {
// Toast.makeText(getApplicationContext(),"Internet Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.VISIBLE);
} else {
// Toast.makeText(getApplicationContext(),"Internet Not Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.GONE);
}
fbCommentview.setWebViewClient(new myWebClient());
fbCommentview.getSettings()
.setJavaScriptCanOpenWindowsAutomatically(true);
fbCommentview.getSettings().setJavaScriptEnabled(true);
fbCommentview.getSettings().setDefaultFontSize(18);
fbCommentview.setWebChromeClient(new WebChromeClient());
fbCommentview.getSettings().setPluginState(PluginState.ON_DEMAND);
fbCommentview.loadUrl(articleComment);
System.out.println("Title" + t);
System.out.println("Content" +c);
LinearLayout layout = new LinearLayout(SingleArticle.this);
layout.setOrientation(LinearLayout.VERTICAL);
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
layout.setLayoutParams(layoutParams);
layout.addView(titleTxt);
layout.addView(dateTxt);
layout.addView(web1);
layout.addView(fbCommentview);
container.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
}
The Error in LOGCAT
here
TextView titleTxt = (TextView) findViewById(R.id.singletitle);
TextView authorTxt = (TextView) findViewById(R.id.singleauthor);
TextView permalinkTxt = (TextView) findViewById(R.id.singleperlink);
web1 = (WebView) findViewById(R.id.webView2);
fbCommentview = (WebView) findViewById(R.id.fbCommentview);
these all the views contains one parent already.. because of that reason your unable to add it again..if you want to add to the layout here. you have to create those textview like this, instead of getting from xml.
TextView textView = new TextView(MainActivity.this);
and then add to the layout.
Replace below method and try:
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater;
View view = inflater.inflate(R.layout.singlearticle, container, false);
d = d.substring(0, d.length() - 3);
String c = single.content;
c = c.replace("src=\"//", "src=\"https://");
final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(c, ALLOWED_URI_CHARS);
String htmldata = "<!DOCTYPE html><html><style = text/css> img{width:100%!important;height:auto!important;} iframe{width:100sp;max-height:100sp;}a { color:#3366CC; text-decoration: none; } </style> <body style = 'line-height:25px;'>"
+ c + "</body></html>";
TextView titleTxt = (TextView)view.findViewById(R.id.singletitle);
titleTxt.setText(t);
// tt = titleTxt.getText().toString();
Typeface font = Typeface.createFromAsset(getAssets(),
"Helvetica Neue UltraLight.ttf");
Typeface font22 = Typeface.createFromAsset(getAssets(),
"helvetica-neue-regular-1361522098.ttf");
titleTxt.setTypeface(font);
titleTxt.setTypeface(font22);
titleTxt.setTypeface(null, Typeface.BOLD);
TextView authorTxt = (TextView)view.findViewById(R.id.singleauthor);
authorTxt.setText(a);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
authorTxt.setTypeface(font1);
TextView dateTxt = (TextView)view.findViewById(R.id.singledate);
dateTxt.setText(d);
Typeface font2 = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
dateTxt.setTypeface(font2);
TextView permalinkTxt = (TextView)view.findViewById(R.id.singleperlink);
permalinkTxt.setText(p);
permalinkTxt.setVisibility(View.GONE);
// pp = permalinkTxt.getText().toString();
// datep.setVisibility(View.GONE);
web1 = (WebView)view.findViewById(R.id.webView2);
web1.setWebViewClient(new myWebClient());
web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
web1.getSettings().setJavaScriptEnabled(true);
// web1.getSettings().setJavaScriptEnabled(true);
// web1.setInitialScale(65);
web1.getSettings().setDefaultFontSize(18);
web1.setWebChromeClient(new WebChromeClient());
web1.getSettings().setPluginState(PluginState.ON_DEMAND);
// web1.loadUrl("http://dev.skyle.co/fbSDK.php?data="+urlEncoded);
web1.loadData(htmldata, "text/html; charset=utf-8", null);
web1.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent in = new Intent(SingleArticle.this, webview.class);
webclass.webdata = url.toString();
startActivity(in);
return true;
}
});
fbCommentview = (WebView)view.findViewById(R.id.fbCommentview);
/*
* to check internet and show/hide facebook part
*/
checkConnection = new ConnectionDetector(getApplicationContext());
isInternetPresent = checkConnection.isConnectingToInternet();
if (isInternetPresent) {
// Toast.makeText(getApplicationContext(),"Internet Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.VISIBLE);
} else {
// Toast.makeText(getApplicationContext(),"Internet Not Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.GONE);
}
fbCommentview.setWebViewClient(new myWebClient());
fbCommentview.getSettings()
.setJavaScriptCanOpenWindowsAutomatically(true);
fbCommentview.getSettings().setJavaScriptEnabled(true);
fbCommentview.getSettings().setDefaultFontSize(18);
fbCommentview.setWebChromeClient(new WebChromeClient());
fbCommentview.getSettings().setPluginState(PluginState.ON_DEMAND);
fbCommentview.loadUrl(articleComment);
// System.out.println("Title" + t);
// System.out.println("Content" +c);
// LinearLayout layout = new LinearLayout(SingleArticle.this);
// layout.setOrientation(LinearLayout.VERTICAL);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// layout.setLayoutParams(layoutParams);
// layout.addView(titleTxt);
// layout.addView(dateTxt);
// layout.addView(web1);
// layout.addView(fbCommentview);
// container.addView(layout);
return view;
}
Related
can someone help me please? I want a simple method to just enable fullscreen on a video being played in my WebView by simple tapping the video two times or having the fullscreen mode icon in the video player.
Here what I have:
package com.orb.tvdroid;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
/**
* Created by Igor Lima on 29/06/2017.
*/
public class TVDroid extends AppCompatActivity {
WebView TVDroid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tv_droid);
final Activity activity = this;
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#007f00")));
Toast.makeText(getApplicationContext(), "Espere o carregamento da página completar.", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Em seguida, escolha um dos canais disponíveis para começar a transmissão.", Toast.LENGTH_LONG).show();
final String link = this.getIntent().getStringExtra("Link");
TVDroid = (WebView) findViewById(R.id.TVdroid);
this.registerForContextMenu(TVDroid);
WebSettings webSettings = TVDroid.getSettings();
webSettings.setJavaScriptEnabled(true);
TVDroid.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progresso) {
activity.setTitle("TVDroid... " + progresso + "%");
activity.setProgress(progresso * 100);
if (progresso == 100)
activity.setTitle("TVDroid");
}
});
TVDroid.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});
TVDroid.loadUrl(link);
}
}
I already looked into many solutions here, but many of them seems a bit too much for what I want to do. I dont want a full video player function, all I want is just being able to double tap the video player and set it on full screen on my app.
Thanks in advance.
Just did it guys, Thanks Vishal for your idea, here is the final onCreate:
WebView TVDroid;
ProgressDialog carregando;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
this.setTitle("TVDroid");
carregando = new ProgressDialog(TVDroid.this);
carregando.show();
mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
mContentView = findViewById(R.id.fullscreen_content);
mContentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle();
}
});
final Activity activity = this;
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#007f00")));
Toast.makeText(getApplicationContext(), "Espere o carregamento da página completar.", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Em seguida, escolha um dos canais disponíveis para começar a transmissão.", Toast.LENGTH_LONG).show();
final String link = this.getIntent().getStringExtra("Link");
TVDroid = (WebView) findViewById(R.id.TVdroid);
TVDroid.getSettings().setJavaScriptEnabled(true);
TVDroid.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
TVDroid.loadUrl("javascript:(function() { " +
"var head = document.getElementsByTagName('header')[0];"
+ "head.parentNode.removeChild(head);" +
"})()");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});
TVDroid.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progresso) {
carregando.setMessage("Carregando página: " + progresso + "%");
activity.setProgress(progresso * 100);
if (progresso == 100)
carregando.dismiss();
}
});
TVDroid.loadUrl(link);
}
Try this -
Create a new FullscreenActivity -
File -> New -> Activity -> FullscreenActivity
Copy your TVDroid activity code in to FullscreenActivity.
Hi I have an Activity which user open upon click on a TAB. Actually I have a ViewGroup and Tabactivity as Main Activity. on the first tab I have three activity.
Now in an activity I have a list view (custom) populating on Oncreate and a ViewFlipper (only adding view) in Onresume using AsyncTask.
In that asynctask in Pre Execute if I add code for loader it gives error. Also If I do not show the loader the screen is freezing until the Async task finished.
I actually want to load the list view first and then in background run the async task with a loader. Also does not want to freeze the screen.
Here Is My Acivity
package thai.phrasi.ctech.com.phrasi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class WordActivity extends ActionBarActivity {
categories category_obj;
word word_obj;
wordDB wordDb;
WordAdapter adapter;
MediaPlayer mPlayer;
boolean doubleBackToExitPressedOnce = false;
public static ViewFlipper viewFlipper;
public View view;
private static ProgressDialog pleaseWaitDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word);
viewFlipper = new ViewFlipper(this);
viewFlipper.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
TextView txt = (TextView) findViewById(R.id.phraseListHeading);
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
String categoryName = getIntent().getExtras().getString("categoryName").toUpperCase();
wordDb = new wordDB(getApplicationContext());
getAllWords();
//asyncLoadWordList task2 = new asyncLoadWordList(getApplicationContext());
//task2.execute();
txt.setTypeface(font);
txt.setText(categoryName);
ListView wordListView;
wordListView = (ListView)findViewById(R.id.list_view_word);
wordListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = parent.getItemAtPosition(position);
word_obj = (word) o;
if(Integer.valueOf(word_obj.getCategoryId())>=0) {
Intent myIntent = new Intent(WordActivity.this, WordDetailsActivity.class);
myIntent.putExtra("word_obj", word_obj);
myIntent.putExtra("position",position);
myIntent.putExtra("currentClickedId", word_obj.getCsvWordId().toString());
myIntent.putExtra("favouriteFlag",0);
myIntent.putExtra("searchFlag",0);
myIntent.putExtra("searchString", "");
WordActivity.this.startActivity(myIntent);
}
}
});
ImageView backButton = (ImageView) findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent backIntent = new Intent(WordActivity.this, CategoryActivity.class);
View vw = FirstGroup.group.getLocalActivityManager().startActivity("CategoryActivity", backIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
FirstGroup.group.replaceView(vw);
viewFlipper.removeAllViews();
System.runFinalization();
Runtime.getRuntime().gc();
System.gc();
}
});
}
#Override
protected void onPause() {
super.onPause(); // Don't forget this line
stop();
}
public void stop(){
mPlayer=adapter.getMPlayerInstace();
if(mPlayer!=null){
mPlayer.stop();
mPlayer.release();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_word, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onResume(){
super.onResume();
new Thread(new Runnable() {
public void run(){
//All your heavy stuff here!!!
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
if(viewFlipper.getChildCount() == 0) {
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
}).start();
}
public void getAllWords(){
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5), row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
adapter = new WordAdapter(WordActivity.this, words);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
//Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Double tap back button to exit.");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
public class asyncLoadWordList extends AsyncTask<ArrayList<word>, Void, ArrayList<word>>{
private Context mContext;
public asyncLoadWordList(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
/* if (pleaseWaitDialog == null)
pleaseWaitDialog= ProgressDialog.show(WordActivity.this,
"PLEASE WAIT",
"Getting results...",
false);
*/
}
#Override
protected ArrayList<word> doInBackground(ArrayList<word>... params) {
wordDb = new wordDB(mContext);
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
return words;
}
protected void onPostExecute(ArrayList<word> result) {
adapter = new WordAdapter(WordActivity.this, result);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
if (pleaseWaitDialog != null) {
pleaseWaitDialog.dismiss();
pleaseWaitDialog = null;
}
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
public class asyncFlipperView extends AsyncTask<String, Void, String[]> {
String categoryId;
private Context mContext;
wordDB wordDb;
Cursor row;
JSONObject json;
View view;
//private ProgressDialog dialog = new ProgressDialog(WordActivity.this);
public asyncFlipperView(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
}
#Override
protected String[] doInBackground(String... params) {
categoryId = params[0];
json = new JSONObject();
/*do application level task*/
GlobalState state = ((GlobalState) mContext);
state.doAction();
/*Ends*/
wordDb = new wordDB(mContext);
row = wordDb.selectWordList(categoryId);
Log.d("Tag: search result", row.getString(2).toString());
return new String[]{categoryId};
}
protected void onPostExecute(String[] result) {
categoryId = result[0];
ImageView phraseImage = null;
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
row.moveToFirst();
while (!row.isAfterLast()) {
/*phrase Image*/
Integer fileNameLength = row.getString(5).toString().length();
String fileName = row.getString(5).toString();
String imageFile = fileName.substring(0, fileNameLength - 4);
//viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.word_details_flipper_view, null);
TextView tv = (TextView) view.findViewById(R.id.text_english);
tv.setTypeface(font);
tv.setText(row.getString(2).toString());
String picName = row.getString(6).toString();
picName = picName.replace(".png", "");
Uri url1 = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + picName);
ImageView backgroundImage = (ImageView) view.findViewById(R.id.backgroundImage);
Picasso.with(mContext).load(url1).fit().centerCrop().into(backgroundImage);
TextView tvTranslated = (TextView) view.findViewById(R.id.translated_phrase);
tvTranslated.setTypeface(font);
tvTranslated.setText(row.getString(3).toString());
TextView pronounce = (TextView) view.findViewById(R.id.pronounce);
pronounce.setTypeface(font);
pronounce.setText(row.getString(4).toString());
phraseImage = (ImageView) view.findViewById(R.id.phrase_image);
Uri url = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + imageFile);
Picasso.with(mContext).load(url).resize(576, 888).into(phraseImage);
view.setTag(R.string.csvId, row.getString(0).toString());
viewFlipper.addView(view);
row.moveToNext();
}
row.close();
}
private Context getDialogContext() {
Context context;
if (getParent() != null) context = getParent();
else context = WordActivity.this;
return context;
}
}
}
I have this code that receives the RSS feed and displays it into a Row, however, it does not carry over the image once the row has been clicked. How do I achieve this image transfer from the list view to the detailed view.
This is the RSS Reader View
package com.sieae.jamaicaobserver.rss.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* This activity is used to display a list of rss items
*/
public class RssFragment extends Fragment {
private RSSFeed myRssFeed = null;
private Activity mAct;
private LinearLayout ll;
private RelativeLayout pDialog;
public class MyCustomAdapter extends ArrayAdapter<RSSItem> {
public MyCustomAdapter(Context context, int textViewResourceId,
List<RSSItem> list) {
super(context, textViewResourceId, list);
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if(row==null){
LayoutInflater inflater=mAct.getLayoutInflater();
row=inflater.inflate(R.layout.fragment_rss_row, null);
holder = new ViewHolder();
holder.listTitle=(TextView)row.findViewById(R.id.listtitle);
holder.listPubdate=(TextView)row.findViewById(R.id.listpubdate);
holder.listDescription=(TextView)row.findViewById(R.id.shortdescription);
holder.listThumb =(ImageView)row.findViewById(R.id.listthumb);
row.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.listTitle.setText(myRssFeed.getList().get(position).getTitle());
holder.listPubdate.setText(myRssFeed.getList().get(position).getPubdate());
String html = myRssFeed.getList().get(position).getRowDescription();
holder.listDescription.setText(html);
holder.listThumb.setImageDrawable(null);
//get Imageloader
ImageLoader imageLoader = Helper.initializeImageLoader(mAct);
//LayoutInflater inflater = (LayoutInflater) mAct
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View v = inflater.inflate(R.layout.fragment_rss, null);
//ListView listView = (ListView) v.findViewById(R.id.rsslist);
//pausing on scrolling the listview
//boolean pauseOnScroll = true; // or true
//boolean pauseOnFling = true; // or false
//PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
//listView.setOnScrollListener(listener);
String thumburl = myRssFeed.getList().get(position).getThumburl();
if (thumburl != "" && thumburl != null){
//setting the image
imageLoader.displayImage(myRssFeed.getList().get(position).getThumburl(), holder.listThumb, new SimpleImageLoadingListener() {
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (10 > loadedImage.getWidth() || 10 > loadedImage.getHeight()) {
// handle scaling
holder.listThumb.setVisibility(View.GONE);
} else {
holder.listThumb.setVisibility(View.VISIBLE);
}
}
});
} else {
holder.listThumb.setVisibility(View.GONE);
}
return row;
}
}
static class ViewHolder {
TextView listTitle;
TextView listPubdate;
TextView listDescription;
ImageView listThumb;
int position;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ll = (LinearLayout) inflater.inflate(R.layout.fragment_rss, container, false);
setHasOptionsMenu(true);
if ((getResources().getString(R.string.ad_visibility).equals("0"))){
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) ll.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
return ll;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAct = getActivity();
Log.v("INFO", "onAttach() called");
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(){
pDialog = (RelativeLayout) ll.findViewById(R.id.progressBarHolder);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
String weburl = RssFragment.this.getArguments().getString(MainActivity.DATA);
URL rssUrl = new URL(weburl);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListView listview = (ListView) ll.findViewById(R.id.rsslist);
if (myRssFeed != null) {
MyCustomAdapter adapter = new MyCustomAdapter(mAct,
R.layout.fragment_rss_row, myRssFeed.getList());
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
Intent intent = new Intent(mAct,
RssDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed
.getItem(position).getTitle());
bundle.putString("keyDescription",
myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position)
.getLink());
bundle.putString("keyPubdate",
myRssFeed.getItem(position).getPubdate());
bundle.putString("keyThumburl",
myRssFeed.getItem(position).getThumburl());
intent.putExtras(bundle);
startActivity(intent);
}
});
} else {
Helper.noConnection(mAct, true);
}
if (pDialog.getVisibility() == View.VISIBLE) {
pDialog.setVisibility(View.GONE);
//feedListView.setVisibility(View.VISIBLE);
Helper.revealView(listview,ll);
}
super.onPostExecute(result);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.rss_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh_rss:
new MyTask().execute();
return true;
case R.id.info:
//show information about the feed in general in a dialog
if (myRssFeed!=null)
{
String FeedTitle = (myRssFeed.getTitle());
String FeedDescription = (myRssFeed.getDescription());
//String FeedPubdate = (myRssFeed.getPubdate()); most times not present
String FeedLink = (myRssFeed.getLink());
AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
String titlevalue = getResources().getString(R.string.feed_title_value);
String descriptionvalue = getResources().getString(R.string.feed_description_value);
String linkvalue = getResources().getString(R.string.feed_link_value);
if (FeedLink.equals("")){
builder.setMessage(titlevalue+": \n"+FeedTitle+
"\n\n"+descriptionvalue+": \n"+FeedDescription);
} else {
builder.setMessage(titlevalue+": \n"+FeedTitle+
"\n\n"+descriptionvalue+": \n"+FeedDescription +
"\n\n"+linkvalue+": \n"+FeedLink);
};
builder.setNegativeButton(getResources().getString(R.string.ok),null)
.setCancelable(true);
builder.create();
builder.show();
}else{
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
This is the detailed view
package com.sieae.jamaicaobserver.rss.ui;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.sieae.jamaicaobserver.R;
import com.sieae.jamaicaobserver.fav.FavDbAdapter;
import com.sieae.jamaicaobserver.util.WebHelper;
import com.sieae.jamaicaobserver.web.WebviewActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* This activity is used to display details of a rss item
*/
public class RssDetailActivity extends ActionBarActivity {
private WebView wb;
private FavDbAdapter mDbHelper;
private Toolbar mToolbar;
String date;
String link;
String title;
String description;
String favorite;
String listThumb;
#SuppressLint("SetJavaScriptEnabled")#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rss_details);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView detailsTitle = (TextView) findViewById(R.id.detailstitle);
TextView detailsPubdate = (TextView) findViewById(R.id.detailspubdate);
Bundle bundle = this.getIntent().getExtras();
detailsTitle.setText(bundle.getString("keyTitle"));
detailsPubdate.setText(bundle.getString("keyPubdate"));
date = (bundle.getString("keyPubdate"));
link = (bundle.getString("keyLink"));
title = (bundle.getString("keyTitle"));
description = (bundle.getString("keyDescription"));
favorite = (bundle.getString("keyFavorites"));
listThumb = (bundle.getString("keyThumburl"));
wb = (WebView) findViewById(R.id.descriptionwebview);
//parse the html and apply some styles
Document doc = Jsoup.parse(description);
String html = WebHelper.docToBetterHTML(doc, this);;
wb.getSettings().setJavaScriptEnabled(true);
wb.loadDataWithBaseURL(link, html , "text/html", "UTF-8", "");
Log.v("INFO", "Wordpress HTML: " + html);
wb.setBackgroundColor(Color.argb(1, 0, 0, 0));
wb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wb.getSettings().setDefaultFontSize(WebHelper.getWebViewFontSize(this));
wb.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith("http://") || url.startsWith("http://"))) {
Intent mIntent = new Intent(RssDetailActivity.this, WebviewActivity.class);
mIntent.putExtra(WebviewActivity.URL, url);
startActivity(mIntent);
return true;
} else {
Uri uri = Uri.parse(url);
Intent ViewIntent = new Intent(Intent.ACTION_VIEW, uri);
// Verify it resolves
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(ViewIntent, 0);
boolean isIntentSafe = activities.size() > 0;
// Start an activity if it's safe
if (isIntentSafe) {
startActivity(ViewIntent);
}
return true;
}
}
});
if ((getResources().getString(R.string.ad_visibility).equals("0"))) {
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
Button btnOpen = (Button) findViewById(R.id.openbutton);
//Listening to button event
btnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(link));
startActivity(intent);
}
});
Button btnFav = (Button) findViewById(R.id.favoritebutton);
//Listening to button event
btnFav.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
mDbHelper = new FavDbAdapter(RssDetailActivity.this);
mDbHelper.open();
if (mDbHelper.checkEvent(title, description, date, link, "", "", "rss")) {
// Item is new
mDbHelper.addFavorite(title, description, date, link, "", "", "rss");
Toast toast = Toast.makeText(RssDetailActivity.this, getResources().getString(R.string.favorite_success), Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(RssDetailActivity.this, getResources().getString(R.string.favorite_duplicate), Toast.LENGTH_LONG);
toast.show();
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.share:
String html = description;
html = html.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
html = html.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
html = html.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
html = html.replaceAll(" ", "");
html = html.replaceAll("&", "");
html = html.replaceAll("‘", "‘");
String linkvalue = getResources().getString(R.string.item_share_begin);
String seenvalue = getResources().getString(R.string.item_share_middle);
String appvalue = getResources().getString(R.string.item_share_end);
String applicationName = getResources().getString(R.string.app_name);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
//this is the text that will be shared
sendIntent.putExtra(Intent.EXTRA_TEXT, (html + linkvalue + link + seenvalue + applicationName + appvalue));
sendIntent.putExtra(Intent.EXTRA_SUBJECT, title); //you can replace title with a string of your choice
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.share_header)));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.rss_detail_menu, menu);
return true;
}
}
You can send Image via Intent as ByteArray or try loading from URL. Loading from URL is preferred as it will not bring OutOfMemoryException or any other issues while passing large bitmap images via Intent. If image is small, you may pass them via Intent.
The code below shows both the methods. Implement which suits your need or works in your URL case.
Sender Activity
//Download image from thumbUrl to bitmap
URL newurl = new URL(myRssFeed.getItem(position).getThumburl());
Bitmap bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
Intent intent = new Intent(mAct, RssDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
bundle.putString("keyDescription", myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position).getLink());
bundle.putString("keyPubdate",myRssFeed.getItem(position).getPubdate());
//pass image url
bundle.putString("keyThumburl", myRssFeed.getItem(position).getThumburl());
//sent image bitmap byte array
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, bs);
bundle.putByteArray("byteArray", bs.toByteArray());
intent.putExtras(bundle);
startActivity(intent);
Receiver Activity
Bundle bundle = this.getIntent().getExtras();
//load from bitmap bytearray
Bitmap bitmap = BitmapFactory.decodeByteArray(bundle.getByteArray("byteArray"),0,bundle.getByteArray("byteArray").length);
imageView.setImageBitmap(bitmap);
//or load from image url
new LoadImage().execute(bundle.getString("keyThumbUrl"));
Create an AsyncTask to load image to ImageView from URL sent via Intent
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
imageView.setImageBitmap(image);
} else{
Toast.makeText(RssDetailActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
Two activities are sending data to each other.
The first activity has a custom list view. The second has one text view and three buttons to increase and decrease a value.
When I click on the first activity, the second activity opens. The second activity increases the text view value and clicked the button. Data goes to the first activity. Same process again.
My problem is that the total value is not displayed in the first activity.
How can i show all increase and decrease values from the second activity in the first activity?
First activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
public class DetaisRESTActivity extends Activity {
String messagevaluename,valueid,valueid1,valuename,pos;
public String countString=null;
String nameofsubmenu;
public int count=0;
public String message=null;
public String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public SharedPreferences.Editor edit;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detais_rest);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
SharedPreferences preferences=getSharedPreferences("temp1", 1);
// SharedPreferences.Editor editor = preferences.edit();
int na=preferences.getInt("COUNTSTRING1",0);
Log.i("asasassas",""+na);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
// SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
// Reading all contacts
/*
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
*/
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Log.i("postititi",""+position);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
nameofsubmenu=data.getStringExtra("name");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
Log.i("submenu",nameofsubmenu);
//ruppees.setText(message);
//editor.putInt("count",na);
//editor.commit();
//Log.i("asasassasasdsasdasd",""+na);
// mTitleTextView.setText(Arrays.toString(message1));
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("count",message1);
i.putExtra("submenu",nameofsubmenu);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detais_rest, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
public void OnPause(){
super.onPause();
}
}
Second activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String[] cccc;
ImageButton positive,negative;
String position;
static int count = 1;
int tot_amt = 0;
public String countString=null;
String name,price;
String valueid,valueid1,valuename;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
preferences = getSharedPreferences("temp1",1);
editor = preferences.edit();
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
editor.putInt("COUNTSTRING1", count);
editor.commit();
editor.clear();
Log.i("sunder sharma",""+count);
countString= String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
if (count > 1)
count--;
editor.putInt("COUNTSTRING1", count);
editor.commit();
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
SqliteController db = new SqliteController(QuentityActivity.this);
db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));
*/
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
intent.putExtra("name",name);
setResult(2,intent);
finish();//finishing activity
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quentity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Collect the data from second activity and put into below intent .Then you will receive first activity.
Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString); //add data
startActivity(myIntent);
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;
}
}