import android.content.Context;
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import java.util.Date;
import java.util.Locale;
public class Calendarpage extends AppCompatActivity {
//modify here
ActionBar actionBar = null;
CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat ("MMM- yyyy", Locale.getDefault());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
// modify here
ActionBar myActionBar = getSupportActionBar();
if (myActionBar != null) {
myActionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(null);
}
compactCalendar = (CompactCalendarView) findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
Event ev1 = new Event(Color.RED, 1514160000L, "Chirstmas Day");
compactCalendar.addEvent(ev1);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
Context context = getApplicationContext();
if (dateClicked.toString().compareTo("Mon Dec 25 00:00:00 AST 2017") == 0) {
Toast.makeText(context, "Christmas Day", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "No Events Planned That Day", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getSupportActionBar.setTitle(String.valueOf(dateFormatMonth.format(firstDayOfNewMonth)));
}
});
}
}
now added the changes you made but the getSupportActionBar. is in red? its just asking me to create local variables when right clicking. very stressed with this as I can't move on until this page works.. as I still need to be able to add events to dates
Try to make this change
In your OnCreate :
ActionBar myActionBar = getSupportActionBar();
if (myActionBar != null) {
myActionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(null);
}
In your setListener
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getSupportActionBar().setTitle(String.valueOf(
dateFormatMonth.format(firstDayOfNewMonth)));
}
Good luck
EDIT try this
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
setNewTitleBar(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
private void setNewTitleBar(String newTitle) {
getSupportActionBar().setTitle(newTitle);
}
}
Related
I was trying to understand how to make a search functions in an app. I go through the Creating a Search Interface documentation, but its quite hard and yea i need help. However, i do succeed to just create a search interface, displaying results based from a string arrray. It does work, but it doesnt had any activity behind it or any intent. It more like a simple text-search. I just wondering can i put int that can simultaneously work with string ?
Or any solution and ideas, really appreciate it.
for now here is my homefragment class
package com.example.testtt;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class HomeFragment extends Fragment implements View.OnClickListener {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
//define
RelativeLayout drawerlayouthome;
ListView list;
ListViewAdapter adapter;
SearchView editsearch;
ArrayList<DoaSearchIndex> arrayList = new ArrayList<DoaSearchIndex>();
String[] doasearchindex = getActivity().getResources().getStringArray(R.array.doasearchindex);
//locatelistview
list = v.findViewById(R.id.searchlistview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
list.setVisibility(View.INVISIBLE);
}
});
for (int i = 0; i < doasearchindex.length; i++) {
DoaSearchIndex doaSearchIndex = new DoaSearchIndex(doasearchindex[i]);
arrayList.add(doaSearchIndex);
}
//pass result to listviewadapter.class
adapter = new ListViewAdapter(this.getActivity(), arrayList);
//binds adapter to listview
list.setAdapter(adapter);
list.setVisibility(View.INVISIBLE);
//locatesearchview
editsearch = v.findViewById(R.id.searchview);
editsearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(TextUtils.isEmpty(newText)){
list.clearTextFilter();
adapter.filter("");
list.setVisibility(View.INVISIBLE);
} else {
adapter.filter(newText);
list.setVisibility(View.VISIBLE);
}
return true;
}
});
drawerlayouthome = v.findViewById(R.id.drawer_layouthome);
drawerlayouthome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.setVisibility(View.INVISIBLE);
editsearch.clearFocus();
}
});
//definingcardview
CardView doacard = v.findViewById(R.id.doacard);
CardView ziarahcard = v.findViewById(R.id.ziarahcard);
//setcardviewlistener
doacard.setOnClickListener(this);
ziarahcard.setOnClickListener(this);
return v;
}
#Override
public void onClick(View view) {
Intent i ;
switch (view.getId()) {
case R.id.doacard:
i = new Intent(getActivity(), listdoa.class);
startActivity(i);
break;
case R.id.ziarahcard:
i = new Intent(getActivity(), listziarah.class);
startActivity(i);
break;
}
}
}
and my listviewadapter
package com.example.testtt;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ListViewAdapter extends BaseAdapter {
//Declare variables first
Context mContext;
LayoutInflater inflater;
private List<DoaSearchIndex> doaSearchIndexList = null;
private ArrayList<DoaSearchIndex> arrayList;
public ListViewAdapter(Context context, List<DoaSearchIndex> doaSearchIndexList) {
mContext = context;
this.doaSearchIndexList = doaSearchIndexList;
inflater = LayoutInflater.from(mContext);
this.arrayList = new ArrayList<DoaSearchIndex>();
this.arrayList.addAll(doaSearchIndexList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return doaSearchIndexList.size();
}
#Override
public DoaSearchIndex getItem(int position) {
return doaSearchIndexList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(doaSearchIndexList.get(position).getDoaSearchIndex());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
doaSearchIndexList.clear();
if (charText.length() == 0) {
doaSearchIndexList.addAll(arrayList);
} else {
for (DoaSearchIndex wp : arrayList) {
if (wp.getDoaSearchIndex().toLowerCase(Locale.getDefault()).contains(charText)) {
doaSearchIndexList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
and my doasearchindex class
package com.example.testtt;
public class DoaSearchIndex {
private String doaSearchIndex;
public DoaSearchIndex(String doaSearchIndex) {
this.doaSearchIndex = doaSearchIndex;
}
public String getDoaSearchIndex() {
return this.doaSearchIndex;
}
}
This code is not working and my paystack payment gateway is not showing, though it displays the spinner but will not show the form for card input.
Please I need a complete code that will help me get my job done:
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
WebView newWebView = new WebView(WebpageActivity.this);
newWebView.getSettings().setJavaScriptEnabled(true);
newWebView.getSettings().setSupportZoom(true);
newWebView.getSettings().setBuiltInZoomControls(true);
newWebView.getSettings().setPluginState(PluginState.ON);
newWebView.getSettings().setSupportMultipleWindows(true);
view.addView(newWebView);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
newWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
return true;
}
}
});
Well, this code should work when pasted on your MainActivity file of your android webview project.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.net.Uri;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
public class MainActivity extends Activity {
private WebView webView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webView.setInitialScale(1);
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowContentAccess(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setPluginState(PluginState.ON);
webSettings.setSupportMultipleWindows(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
WebViewClientImpl webViewClient = new WebViewClientImpl(this);
webView.setWebViewClient(webViewClient);
webView.loadUrl("https://www.your_url.com/");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
this.webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public class WebViewClientImpl extends WebViewClient {
private Activity activity = null;
public WebViewClientImpl(Activity activity) {
this.activity = activity;
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if(url.indexOf("your_url") > -1 ) return false;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
}
}
}
Now, after pasting the above code you need to use the PHP paystack integration this time and not the javascript paystack integration initialization and callback functions.
At this point you only need to worry about your sessions.
Tested And Confirmed.
I want to use this module https://github.com/nucleartux/react-native-date for react-native. I trying to install this module, but when I do step 4 (Register React Package) I have an error with build.
Error message:
MainActivity.java:31: error: incompatible types: MainActivity cannot be converted to FragmentActivity
.addPackage(new ReactDatePackage(this))
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
:app:compileDebugJavaWithJavac FAILED
* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed.
Code with error:
package com.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import me.nucleartux.date.ReactDatePackage;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends Activity implements
DefaultHardwareBackBtnHandler {
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.addPackage(new ReactDatePackage(this))
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "myapp", null);
setContentView(mReactRootView);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
#Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
#Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onPause();
}
}
#Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onResume(this);
}
}
}
Can you help me to fix this problem, please?
In the doc at step 4, you also have to make your MainActivity extend FragmentActivity:
public class MainActivity extends FragmentActivity implements DefaultHardwareBackBtnHandler { // ! extends from FragmentActivity
(yours only extend Activity)
I had Successful login to a website using jsoup and I obtained cookies from Jsoup cookies function in Map but I am struck at something.After successful login I Want to open a webpage of the website in the webview but the webpage redirects to the login page because cookies are not successfully passed to the webview and I don't know why. The page wants cookies of successful login to load that page
Here is the login page url.
http://111.68.99.8/StudentProfile/
and page I want to load after Successful Login
http://111.68.99.8/StudentProfile/PersonalInfo.aspx
Here is the MainActivity.java
package com.example.ebad.bu;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends ActionBarActivity {
String url = "http://111.68.99.8/StudentProfile/";
Map<String, String> logingcookies;
HashMap<String,String> hashMap;
ProgressDialog progressDialog,progressDialoge;
Button login, personal;
TextView Enrollement, password, E;
String enrol = "";
String pass = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button) findViewById(R.id.login_button);
personal = (Button) findViewById(R.id.pers);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Enrollement = (TextView) findViewById(R.id.Enrollment);
enrol = Enrollement.getText().toString();
password = (TextView) findViewById(R.id.password);
pass = password.getText().toString();
new Title().execute();
}
});
}
private class Title extends AsyncTask<Void, Void, Void> {
String title;
String father;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Title");
progressDialog.setMessage("Loading");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Connection.Response loginForm = Jsoup.connect(url).method(Connection.Method.GET).timeout(1000).execute();
Document doc = loginForm.parse();
String viewstate = doc.select("input[name=__VIEWSTATE]").attr("value");
String stategenerator = doc.select("input[name=__VIEWSTATEGENERATOR]").attr("value");
String Eventvalidation = doc.select("input[name=__EVENTVALIDATION]").attr("value");
doc = Jsoup.connect(url)
.data("__LASTFOCUS", "")
.data("__EVENTTARGET", "")
.data("__EVENTARGUMENT", "")
.data("__VIEWSTATE", viewstate)
.data("__VIEWSTATEGENERATOR", stategenerator)
.data("__EVENTVALIDATION", Eventvalidation)
.data("ctl00$Body$ENROLLMENTTextBox$tb", enrol)
.data("ctl00$Body$ENROLLMENTTextBox$cv_vce_ClientState", "")
.data("ctl00$Body$PasswordTextBox$tb", pass)
.data("ctl00$Body$PasswordTextBox$cv_vce_ClientState", "")
.data("ctl00$Body$LoginButton", "Login")
.cookies(loginForm.cookies())
.post();
logingcookies = loginForm.cookies();
title = doc.select("div[id=ctl00_Accounts]").html();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
/*Intent showadditionmenu = new Intent(MainActivity.this,Per.class);
//showadditionmenu.putStringArrayListExtra("logingcookies", (ArrayList<String>) logingcookies);
showadditionmenu.putExtra("logingcookies", String.valueOf(logingcookies));
MainActivity.this.startActivity(showadditionmenu);*/
/* Intent i = new Intent(MainActivity.this,Per.class);
i.putExtra("hashMap",hashMap );
startActivity(i);
*/
hashMap = new HashMap<String,String>(logingcookies);
Intent i = new Intent(MainActivity.this,wee.class);
i.putExtra("hashMap",hashMap );
startActivity(i);
/* E = (TextView) findViewById(R.id.message);
E.setText(title);
progressDialog.dismiss();*/
}
}
}
I have passed the saved cookie to the activity that load the webpage in webivew.. Here is the other activity;
Wee.java
package com.example.ebad.bu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Ebad on 11/8/2015.
*/
public class wee extends Activity {
String url= "http://111.68.99.8/StudentProfile/PersonalInfo.aspx";
HashMap<String ,String> hashMap;
Map<String,String> map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
Intent intent = getIntent();
hashMap = (HashMap<String,String>) intent.getSerializableExtra("hashMap");
WebView webView = (WebView) findViewById(R.id.webviewe);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url,hashMap);
}
}
Is there any way that I can view that webpage without logging in again to the webview?
Haven't tested it, but using CookieManager ahould work.
Usage should be something like this:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie(); //optional
cookieManager.setAcceptCookie(true);
Then loop over your cookies using the setCookie method.
Note: If useing lollipop and up you should also use setAcceptThirdPartyCookies.
Good luck.
I have an XML file that consists of a title, a link to the image, and description.
exp.
<?xml ?>
<wrap>
<content>
<title>Title</title>
<img>link of image</img>
<desc>Descrioption</desc>
</content>
<content>
<title>Title</title>
<img>link of image</img>
<desc>Descrioption</desc>
</content>
<content>
<title>Title</title>
<img>link of image</img>
<desc>Description</desc>
</content>
</wrap>
I want the title shown on Listview which when clicked will open a detail page complete with titles, pictures, and descriptions .
examples such as those found at the following link Google's developer:
http://developer.android.com/design/material/videos/ContactsAnim.mp4
this is my full code
Anggra.java (this is main activity of my project)
package com.tolhedo.akew.anggra;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.viewpagerindicator.TitlePageIndicator;
public class Anggra extends ActionBarActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
TitlePageIndicator titlePageIndicator;
private static final int numPages = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anggra);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
titlePageIndicator = (TitlePageIndicator)findViewById(R.id.titles);
titlePageIndicator.setViewPager(mViewPager);
}
#Override
public void onBackPressed() {
if (mViewPager.getCurrentItem() == 0){
super.onBackPressed();
}
else {
mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_anggra, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new Welcome();
getPageTitle(position);
break;
case 1:
fragment = new ViewContent();
getPageTitle(position);
break;
case 2:
fragment = new ItemFragment();
getPageTitle(position);
break;
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return numPages;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_anggra, container, false);
return view;
}
}
}
ItemFragment.java
package com.tolhedo.akew.anggra;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.tolhedo.akew.anggra.dummy.ResourcesAdapter;
public class ItemFragment extends Fragment{
public ItemFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item, container, false);
listView = (AbsListView) view.findViewById(R.id.list_item);
textView = (TextView) view.findViewById(R.id.name);
Resources resources = getActivity().getResources();
ResourcesAdapter resourcesAdapter = new ResourcesAdapter(resources, view, getActivity());
resourcesAdapter.stringResource();
return view;
}
}
ViewContent.java
package com.tolhedo.akew.anggra;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.tolhedo.akew.anggra.dummy.CustomView;
import com.tolhedo.akew.anggra.dummy.FullView;
import com.tolhedo.akew.anggra.dummy.ParsedDataSet;
import com.tolhedo.akew.anggra.dummy.XmlContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class ViewContent extends Fragment{
private TextView textView;
private AbsListView listView;
private ArrayList<ParsedDataSet> itemList;
private ProgressDialog pDialog;
private XmlContentHandler xmlContentHandler;
private String url = "http://oscom.meximas.com/imagelistview.xml";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_view, container, false);
textView = (TextView) view.findViewById(R.id.content);
listView = (AbsListView) view.findViewById(R.id.listView1);
doParsing(view);
itemList = new ArrayList<>();
setListViewClick(listView);
return view;
}
public void doParsing(View view){
if (isNetworkAvailable()){
textView.setText("Loading...");
new AsyncData().execute(url);
}
else
{
showToast("No Network Connection!!!");
}
}
private void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);
if (connectivity == null)
{
return false;
}
else
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++)
{
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
private class AsyncData extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute()
{
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
try
{
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlContentHandler = new XmlContentHandler();
xmlReader.setContentHandler(xmlContentHandler);
URL _url = new URL(params[0]);
xmlReader.parse(new InputSource(_url.openStream()));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
textView.setText("Read all epic episode of Anggra");
if (pDialog != null && pDialog.isShowing()){
pDialog.dismiss();
}
itemList = xmlContentHandler.getListItem();
if (null != itemList && itemList.size() != 0){
for (int index = 0; index < itemList.size(); index++){
ParsedDataSet parsedDataSet = itemList.get(index);
}
}
itemList = xmlContentHandler.getListItem();
listView.setAdapter(new CustomView(getActivity(),itemList));
}
}
private void setListViewClick (AbsListView listView){
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
itemList = xmlContentHandler.getListItem();
if (null != itemList && itemList.size() != 0){
for (int index = 0; index < itemList.size(); index++){
ParsedDataSet parsedDataSet = itemList.get(index);
textView.setText(parsedDataSet.getDesc());
Intent intent = new Intent(getActivity(), FullView.class);
startActivity(intent);
}
}
}
});
}
public void loadImg(String url, ImageView img){
try{
URL url1 = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
img.setImageBitmap(BitmapFactory.decodeStream(inputStream));
return;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
CustomView.java
package com.tolhedo.akew.anggra.dummy;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.tolhedo.akew.anggra.R;
public class CustomView extends BaseAdapter {
Context mContext;
ArrayList<ParsedDataSet> dataSets;
LayoutInflater mInflater;
public CustomView(Context context, ArrayList<ParsedDataSet> itemList)
{
mContext = context;
dataSets = itemList;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return dataSets.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if(convertView == null){
vh= new ViewHolder();
convertView = mInflater.inflate(R.layout.custom_view, parent, false);
vh.tv1 = (TextView) convertView.findViewById(R.id.textView1);
vh.tv2 = (TextView) convertView.findViewById(R.id.textView2);
vh.tv3 = (TextView) convertView.findViewById(R.id.textView3);
vh.tv4 = (TextView) convertView.findViewById(R.id.textView4);
vh.img = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(vh);
}
else {
vh = (ViewHolder) convertView.getTag();
}
ParsedDataSet parsedDataSet = dataSets.get(position);
vh.tv1.setText(parsedDataSet.getTitle());
vh.tv2.setText(parsedDataSet.getDesc());
vh.tv3.setText(parsedDataSet.getPubDate());
vh.tv4.setText(parsedDataSet.getLink());
return convertView;
}
static class ViewHolder
{
TextView tv1,tv2,tv3, tv4;
ImageView img;
}
}
ParseDataSet.java
package com.tolhedo.akew.anggra.dummy;
/**
* Created by akew on 1/14/2015.
*/
public class ParsedDataSet {
private String id;
private String title;
private String desc;
private String pubDate;
private String link;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
ResourcesAdapter.java
package com.tolhedo.akew.anggra.dummy;
import android.app.Activity;
import android.content.res.Resources;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.tolhedo.akew.anggra.R;
/**
* Created by akew on 1/8/2015.
*/
public class ResourcesAdapter {
Resources mResources;
View mView;
Activity mActivity;
String[] strings;
AbsListView mListView;
ListAdapter mAdapter;
TextView mTextView;
public ResourcesAdapter(Resources resources, View view, Activity activity){
mActivity = activity;
mResources = resources;
mView = view;
mListView = (AbsListView) view.findViewById(android.R.id.list);
}
public void stringResource(){
strings = mResources.getStringArray(R.array.list_title);
mAdapter = new ArrayAdapter<>(mActivity
, android.R.layout.simple_list_item_1
, android.R.id.text1
, strings);
mListView.setAdapter(mAdapter);
setListViewClick(mListView);
}
private void setListViewClick(AbsListView mListView){
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mTextView = (TextView) view;
Toast.makeText(mActivity
, mTextView.getText()
, Toast.LENGTH_SHORT).show();
}
});
}
}
XmlContentHandler.java
package com.tolhedo.akew.anggra.dummy;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
/**
* Created by akew on 1/14/2015.
*/
public class XmlContentHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = "";
ParsedDataSet parsedDataSet = null;
private ArrayList<ParsedDataSet> itemList = new ArrayList<>();
public ArrayList<ParsedDataSet> getListItem() {
return itemList;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentElement = true;
currentValue = "";
if (localName.equals("item")){
parsedDataSet = new ParsedDataSet();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
if (localName.equals("id")){
parsedDataSet.setId(currentValue);
}
else if (localName.equals("title")){
parsedDataSet.setTitle(currentValue);
}
else if (localName.equals("desc")){
parsedDataSet.setDesc(currentValue);
}
else if (localName.equals("pubDate")){
parsedDataSet.setPubDate(currentValue);
}
else if (localName.equals("link")){
parsedDataSet.setLink(currentValue);
}
else if (localName.equals("item")){
itemList.add(parsedDataSet);
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement){
currentValue = currentValue + new String(ch, start, length);
}
}
}
thank you for help