How to select an Object in my Listview - android

I have a RemoteCar Control app where on the MainActivity page there is a button "location" which you can click on to get redirected into another activity (locationActivity). In this activity im displaying a JSON File in a Listview and now I want to click on those objects to select them and display the location on the main page in something like a simple TextView nothing special. How can I do that?
This is my location page:
public class location extends AppCompatActivity {
private String TAG = location.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> locationList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
locationList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(location.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "url";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONArray locations = jsonObj.getJSONArray("");
JSONArray locations_ = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < locations_.length(); i++) {
JSONObject c = locations_.getJSONObject(i);
String type = c.getString("type");
String name = c.getString("name");
String address = c.getString("address");
String lat = c.getString("lat");
String lon = c.getString("lon");
String icon;
if(c.has("icon")){
//your json is having "icon" Key, get the value
icon = c.getString("icon");
}
else{
//your json is NOT having "icon" Key, assign a dummy value
icon = "/default/icon_url()";
}
// tmp hash map for single contact
HashMap<String, String> location = new HashMap<>();
// adding each child node to HashMap key => value
location.put("type", type);
location.put("name", name);
location.put("address", address );
location.put("lat", lat);
location.put("lon", lon);
location.put("icon", icon);
// adding contact to contact list
locationList.add(location);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(location.this, locationList,
R.layout.list_item, new String[]{"type", "name", "address", "lat", "lon", "icon"},
new int[]{R.id.type, R.id.name, R.id.address, R.id.lat, R.id.lon, R.id.icon});
lv.setAdapter(adapter);
}
}
and this is my MainActivity page
public class MainActivity extends AppCompatActivity {
public ProgressBar fuelBar;
public Button lockButton;
public Button engButton;
public Button refuelButton;
public Button locationButton;
public SeekBar seekBarButton;
public TextView seekText;
int incFuel = 0;
final String FUELBAR = "fuelBar";
final String AC_BARTEXT = "acBarText";
final String AC_BAR = "acBar";
final String REFUELBUTTON = "refuelButton";
final String STARTENGINE = "startEngineButton";
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationButton = (Button) findViewById(R.id.locationB);
lockButton = (Button) findViewById(R.id.lockB);
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
fuelBar.setMax(100);
fuelBar.setProgress(30);
refuelButton.setText(R.string.refuelB);
lockButton.setText(R.string.lockB);
locationButton.setText(R.string.locationB);
engButton.setText(R.string.engB);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
sharedPref = getPreferences(Context.MODE_PRIVATE);
editor = sharedPref.edit();
seek_bar();
lockPage();
locationPage();
}
#Override
protected void onPause(){
super.onPause();
editor.putInt(FUELBAR, fuelBar.getProgress());
editor.commit();
String tmpAC = "AC : " + String.valueOf(seekBarButton.getProgress()+18) + "°";
editor.putString(AC_BARTEXT, tmpAC);
editor.commit();
editor.putInt(AC_BAR, seekBarButton.getProgress());
editor.commit();
editor.putString(REFUELBUTTON, refuelButton.getText().toString());
editor.commit();
editor.putString(STARTENGINE, engButton.getText().toString());
editor.commit();
}
#Override
public void onResume(){
super.onResume();
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
incFuel = sharedPref.getInt(FUELBAR, 0);
fuelBar.setProgress(incFuel);
seekText = (TextView) findViewById(R.id.seekText);
String tmpAC = sharedPref.getString(AC_BARTEXT, "error");
seekText.setText(tmpAC);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
int tmpInt = sharedPref.getInt(AC_BAR, 18);
seekBarButton.setProgress(tmpInt);
tmpAC = sharedPref.getString(REFUELBUTTON, "REFUEL");
refuelButton.setText(tmpAC);
tmpAC = sharedPref.getString(STARTENGINE, "START ENGINE");
engButton.setText(tmpAC);
}
#Override
public void onStop(){
super.onStop();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.engB:
if (engButton.getText() == "ENGINE RUNNING") {
engButton.setText("START ENGINE");
} else {
if (fuelBar.getProgress() > 0) {
Toast.makeText(MainActivity.this, "starting engine..", Toast.LENGTH_SHORT).show();
engButton.setText("ENGINE RUNNING");
if (fuelBar.getProgress() >= 10) {
incFuel = fuelBar.getProgress();
incFuel -= 10;
fuelBar.setProgress(incFuel);
if (fuelBar.getProgress() < 100)
refuelButton.setText("REFUEL");
}
} else if (fuelBar.getProgress() == 0) {
Toast.makeText(MainActivity.this, "no fuel", Toast.LENGTH_SHORT).show();
engButton.setText("EMPTY GASTANK");
} else
engButton.setText("START ENGINE");
}
break;
case R.id.refuelB:
if (fuelBar.getProgress() == 0) {
engButton.setText("START ENGINE");
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else if (fuelBar.getProgress() < 100) {
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else {
Toast.makeText(MainActivity.this, "tank is full", Toast.LENGTH_SHORT).show();
refuelButton.setText("FULL");
}
break;
}
}
public void seek_bar() {
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
seekBarButton.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNum;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressNum = progress;
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
});
}
public void lockPage() {
lockButton = (Button) findViewById(R.id.lockB);
lockButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent lockPage = new Intent(MainActivity.this, lockDoor.class);
startActivity(lockPage);
}
});
}
public void locationPage() {
locationButton = (Button) findViewById(R.id.locationB);
locationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent locationPage = new Intent(MainActivity.this, location.class);
startActivity(locationPage);
}
});
}
}
Sorry for the wall of code I'm always unsure how much information to provide.

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MyActivity.this, "location:" + " "+ stringList[position] + " " + "hauptbahnhof selected", Toast.LENGTH_SHORT).show();
}
});
define your list of string as private out of onCreate

Related

Hide Adsense ad space in android app webview by its id?

I want to hide space caused by the google AdSense ads in the android app while fetching data from its WordPress site through WebView. My Code is:
public class PostViewActivity extends AppCompatActivity {
private static final String TAG = PostViewActivity.class.getSimpleName();
public static final String TAG_SEL_POST_ID = "post_id";
public static final String TAG_SEL_POST_TITLE = "post_title";
public static final String TAG_SEL_POST_IMAGE = "post_image";
private String commentsNumber;
private String selectedPostID, selectedPostTitle;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private ImageButton fab;
private TextView post_name;
private TextView post_content;
private TextView post_author;
private ImageView postImageView;
private String post_image, objURL, objTitle;
private Integer commentsCount;
private TextView timestamp;
private NetworkImageView profilePic;
private ShareActionProvider mShareActionProvider;
private WebView post_contentHTML;
private Boolean user_can_comment = true;
private Spanned spannedContent;
private ProgressBar pbLoader;
private LinearLayout llayout;
private Integer OC = 0;
String html;
Gson gson;
Map<String, Object> mapPost;
Map<String, Object> mapTitle;
Map<String, Object> mapContent;
//----------Exit and Banner Ad----------------------------------
private InterstitialAd interstitial;
private AdView mAdView,mAdView1;
private Toolbar toolbar;
String URL ="http://www.asiannews.co.in/_STORY_ID_/";
public static void navigate(AppCompatActivity activity, View transitionImage, Post post) {
Intent intent = new Intent(activity, PostViewActivity.class);
intent.putExtra(TAG_SEL_POST_IMAGE, post.getImge());
intent.putExtra(TAG_SEL_POST_TITLE, post.getName());
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionImage, TAG_SEL_POST_IMAGE);
ActivityCompat.startActivity(activity, intent, options.toBundle());
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString(TAG_SEL_POST_ID, selectedPostID);
savedInstanceState.putString(TAG_SEL_POST_TITLE, selectedPostTitle);
Log.d(TAG, savedInstanceState.toString());
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.d(TAG, "Restored: " + savedInstanceState.toString());
selectedPostID = (String) savedInstanceState.getString(TAG_SEL_POST_ID);
selectedPostTitle = (String) savedInstanceState.getString(TAG_SEL_POST_TITLE);
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
//Get a Tracker (should auto-report)
if (Const.Analytics_ACTIVE) {
AnalyticsUtil.sendScreenName(this, TAG);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initActivityTransitions();
setContentView(R.layout.activity_post_view);
//Forcing RTL Layout, If Supports and Enabled from Const file
Utils.forceRTLIfSupported(this);
ActivityCompat.postponeEnterTransition(this);
final String id = getIntent().getExtras().getString("id");
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
//Get and Set the Post Title
String itemTitle = getIntent().getStringExtra(TAG_SEL_POST_TITLE);
setTitle(Html.fromHtml(itemTitle));
if (savedInstanceState == null) {
if (getIntent().getExtras() == null) {
selectedPostID = null;
selectedPostTitle = "Unknown Error";
} else {
selectedPostID = getIntent().getExtras().getString(TAG_SEL_POST_ID);
selectedPostTitle = getIntent().getExtras().getString(TAG_SEL_POST_TITLE);
}
} else {
Log.d(TAG, "Resume: " + savedInstanceState.toString());
selectedPostID = (String) savedInstanceState.getString(TAG_SEL_POST_ID);
selectedPostTitle = (String) savedInstanceState.getString(TAG_SEL_POST_TITLE);
/*selectedPostID = (String) savedInstanceState.getSerializable(TAG_SEL_POST_ID);
selectedPostTitle = (String) savedInstanceState.getSerializable(TAG_SEL_POST_TITLE);*/
}
//Setting up Fields Display
fab = (ImageButton) findViewById(R.id.fab);
post_name = (TextView) findViewById(R.id.title);
timestamp = (TextView) findViewById(R.id.timestamp);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/GenR102.ttf");
post_name.setTypeface(font);
float density = getResources().getDisplayMetrics().density;
int leftPadding = (int) (20 * density);
Configuration config = getResources().getConfiguration();
if (ViewCompat.getLayoutDirection(post_name) == ViewCompat.LAYOUT_DIRECTION_RTL) {
//post_name.setPadding(leftPadding,R.dimen.spacing_large,0,0);
post_name.setPadding(leftPadding, 0, 0, 0);
} else {
post_name.setPadding(0, 0, leftPadding, 0);
}
post_content = (TextView) findViewById(R.id.description);
post_contentHTML=(WebView) findViewById(R.id.descriptionHTML);
String post_con = "<!DOCTYPE html>" +
"<html lang=\"en\">" +
" <head>" +
" <meta charset=\"utf-8\">" +
" </head>" +
" <body>"+ "<script>" +
"<ins>" +"</ins>" +
"</script>"+"<script>"+
"</script>"
+"#content" +
" </body>" +
"</html>" ;
html= "<html><body style='margin:0;padding:0;'><script type='text/javascript' src='http://asiannews.co.in/myads.html'></script></body></html>";
if (!Const.ShowPostAsWebView) {
post_content.setMovementMethod(LinkMovementMethod.getInstance());
Typeface font_postcontent = Typeface.createFromAsset(getAssets(), "fonts/OSRegular.ttf");
post_content.setTypeface(font_postcontent);
String url = "http://www.asiannews.co.in/bp4a-api/v1/post/_STORY_ID_/";
/* StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
gson = new Gson();
mapPost = (Map<String, Object>) gson.fromJson(s, Map.class);
mapTitle = (Map<String, Object>) mapPost.get("title");
mapContent = (Map<String, Object>) mapPost.get("content");
post_content.setText(mapTitle.get("name").toString());
post_contentHTML.loadData(mapContent.get("description").toString(), "text/html", "UTF-8");
// progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// progressDialog.dismiss();
Toast.makeText(PostViewActivity.this,id, Toast.LENGTH_LONG).show();
}
});
RequestQueue rQueue = Volley.newRequestQueue(PostViewActivity.this);
rQueue.add(request);*/
} else {
post_contentHTML.setVisibility(View.VISIBLE);
WebSettings webSettings = post_contentHTML.getSettings();
post_contentHTML.getSettings().setJavaScriptEnabled(true);
// post_contentHTML.addJavascriptInterface(post_contentHTML,post_contentHTML);
post_contentHTML.loadUrl("http://www.asiannews.co.in/bp4a-api/v1/post/_STORY_ID_/");
post_contentHTML.getSettings().setAllowContentAccess(true);
post_contentHTML.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
post_contentHTML.getSettings().setLoadsImagesAutomatically(true);
post_contentHTML.getSettings().setDefaultTextEncodingName("utf-8");
post_contentHTML.getSettings().setUseWideViewPort(true);
post_contentHTML.getSettings().getMixedContentMode();
post_contentHTML.getSettings().setLoadWithOverviewMode(true);
post_contentHTML.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
post_contentHTML.loadDataWithBaseURL(" ",post_con,"text/html","utf-8"," ");
post_contentHTML.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
post_contentHTML.setWebChromeClient(new WebChromeClient());
post_contentHTML.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
}
public void onPageFinished(WebView view, String url) {
post_contentHTML.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('adsbygoogle')[0].style.display='none'; " +
"})()");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
// post_contentHTML.loadUrl(URL);
// post_contentHTML.loadData(html,"text/html","utf-8");
// post_contentHTML.loadUrl("http://asiannews.co.in/myads.html");
if (Build.VERSION.SDK_INT >= 16) {
webSettings.setAllowFileAccessFromFileURLs(false);
webSettings.setAllowUniversalAccessFromFileURLs(false);
}
}
post_author = (TextView) findViewById(R.id.post_author);
postImageView = (ImageView) findViewById(R.id.image);
profilePic = (NetworkImageView) findViewById(R.id.profilePic);
//Setting up Post Image and Toolbar Activity
//final ImageView image = (ImageView) findViewById(R.id.image);
/*ViewCompat.setTransitionName(postImageView, TAG_SEL_POST_IMAGE);
Bitmap bitmap = ((BitmapDrawable) postImageView.getDrawable()).getBitmap();
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
applyPalette(palette, postImageView);
}
});*/
//Setting Up Post Admob Banner
////Standard Banner
mAdView = (AdView) findViewById(R.id.adView);
if (Const.ADMOBService_ACTIVE) {
//----------Exit Ad----------------------------------
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.unit_id_interstitial));
AdRequest adRequestInterstitial = new AdRequest.Builder().build();
interstitial.loadAd(adRequestInterstitial);
//----------Exit Ad----------------------------------
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
mAdView.setVisibility(View.VISIBLE);
}
});
} else {
mAdView.setVisibility(View.GONE);
}
getPost();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initActivityTransitions() {
if (Utils.isLollipop()) {
Slide transition = new Slide();
transition.excludeTarget(android.R.id.statusBarBackground, true);
getWindow().setEnterTransition(transition);
getWindow().setReturnTransition(transition);
}
}
private void applyPalette(Palette palette, ImageView image) {
int primaryDark = getResources().getColor(R.color.primary_dark);
int primary = getResources().getColor(R.color.primary);
toolbar.setBackgroundColor(primary);
Utils.setStatusBarcolor(getWindow(), primaryDark);
initScrollFade(image);
ActivityCompat.startPostponedEnterTransition(this);
}
private void initScrollFade(final ImageView image) {
final View scrollView = findViewById(R.id.scroll);
setComponentsStatus(scrollView, image);
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
setComponentsStatus(scrollView, image);
}
});
}
private void setComponentsStatus(View scrollView, ImageView image) {
int scrollY = scrollView.getScrollY();
image.setTranslationY(-scrollY / 2);
ColorDrawable background = (ColorDrawable) toolbar.getBackground();
int padding = scrollView.getPaddingTop();
double alpha = (1 - (((double) padding - (double) scrollY) / (double) padding)) * 255.0;
alpha = alpha < 0 ? 0 : alpha;
alpha = alpha > 255 ? 255 : alpha;
background.setAlpha((int) alpha);
float scrollRatio = (float) (alpha / 255f);
int titleColor = getAlphaColor(Color.WHITE, scrollRatio);
toolbar.setTitleTextColor(titleColor);
toolbar.setSubtitleTextColor(titleColor);
}
private int getAlphaColor(int color, float scrollRatio) {
return Color.argb((int) (scrollRatio * 255f), Color.red(color), Color.green(color), Color.blue(color));
}
/**
* It seems that the ActionBar view is reused between activities. Changes need to be reverted,
* or the ActionBar will be transparent when we go back to Main Activity
*/
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void restablishActionBar() {
if (Utils.isLollipop()) {
getWindow().getReturnTransition().addListener(new TransitionAdapter() {
#Override
public void onTransitionEnd(Transition transition) {
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setSubtitleTextColor(Color.WHITE);
toolbar.getBackground().setAlpha(255);
}
});
}
}
#Override
public void onBackPressed() {
restablishActionBar();
if (Const.ADMOBService_ACTIVE) {
displayInterstitial();
}
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
restablishActionBar();
}
return super.onOptionsItemSelected(item);
}
private void getPost() {
//Requesting The Story
String url = null;
url = Const.URL_STORY_PAGE.replace("_STORY_ID_", selectedPostID.replace("P", ""));
//Log.i(TAG, "Taging: " + url);
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.i(TAG, "Taging: " + response.toString());
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
if (response.has("error")) {
String error = response.getString("error");
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
} else {
parseJsonFeed(response);
}
} catch (JSONException es) {
es.printStackTrace();
Toast.makeText(getApplicationContext(), es.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/** Passing some request headers **/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("ApiKey", Const.AuthenticationKey);
return headers;
}
};
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
private void parseJsonFeed(JSONObject feedObj) {
try {
objTitle = feedObj.getString("name");
post_name.setText(Html.fromHtml(objTitle));
commentsCount = feedObj.getInt("comments");
if (feedObj.getString("can_comment") == "no") {
user_can_comment = false;
}
if (!Const.ShowPostAsWebView) {
post_contentHTML.setVisibility(View.GONE);
URLImageParser p = new URLImageParser(this, post_content);
spannedContent = Html.fromHtml(feedObj.getString("story_content"), p, null);
post_content.setText(trimTrailingWhitespace(spannedContent));
} else {
post_content.setVisibility(View.GONE);
post_contentHTML.setVisibility(View.VISIBLE);
post_contentHTML.loadData(html,"text/html","utf-8");
String post_con = "<!DOCTYPE html>" +
"<html lang=\"en\">" +
" <head>" +
" <meta charset=\"utf-8\">" +
" </head>" +
" <body>"+ "<script>" +
"<ins>" +"</ins>" +
"</script>"+"<script>"+
"</script>"
+"#content" +
" </body>" +
"</html>" ;
try {
InputStream in_s = getResources().openRawResource(R.raw.post_format);
byte[] b = new byte[in_s.available()];
in_s.read(b);
post_con = new String(b);
} catch (Exception e) {
e.printStackTrace();
}
post_con = post_con.replace("#title#", feedObj.getString("name"));
post_con = post_con.replace("#content#", feedObj.getString("story_content"));
post_contentHTML.loadData(html, "text/html", "utf-8");
post_contentHTML.loadDataWithBaseURL(null,
post_con,
"text/html",
"UTF-8",
null);
}
if (feedObj.getString("story_content").length() <= 0) {
post_content.setVisibility(View.GONE);
post_contentHTML.setVisibility(View.GONE);
}
post_author.setText(feedObj.getString("author"));
getSupportActionBar().setSubtitle("By " + feedObj.getString("author"));
post_image = feedObj.getString("image");
objURL = feedObj.getString("url");
if (Const.Analytics_ACTIVE) {
AnalyticsUtil.sendEvent(this, "Post View", objTitle, objURL);
}
//Setting Up a Share Intent
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, objTitle + " - " + objURL);
startActivityForResult(Intent.createChooser(shareIntent, "Share via"), 300);
}
});
//setShareIntent(shareIntent);
//Comment Button Click
Button viewComments = (Button) findViewById(R.id.btnViewComments);
commentsNumber = Utils.formatNumber(commentsCount);
viewComments.setText(String.format(getString(R.string.comments_button), commentsNumber));
viewComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(PostViewActivity.this, PostComments.class);
i.putExtra("post_id", selectedPostID.replace("P", ""));
i.putExtra("post_title", getIntent().getStringExtra(TAG_SEL_POST_TITLE));
i.putExtra("commentsCount", commentsCount);
i.putExtra("user_can_comment", user_can_comment);
startActivityForResult(i, 1000);
}
});
//Button Click
Button viewWeb = (Button) findViewById(R.id.btnViewWeb);
if (Const.ShowPostOnExternalBrowser) {
viewWeb.setVisibility(View.VISIBLE);
viewWeb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToUrl(objURL);
}
});
}
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(feedObj.getString("timeStamp")),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
profilePic.setImageUrl(feedObj.getString("profilePic"), imageLoader);
loadConfig();
//pbLoader.setVisibility(View.GONE);
//llayout.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
private void loadConfig() {
if (post_image != null) {
ViewCompat.setTransitionName(postImageView, TAG_SEL_POST_IMAGE);
Picasso.with(this).load(post_image).into(postImageView, new Callback() {
#Override
public void onSuccess() {
Bitmap bitmap = ((BitmapDrawable) postImageView.getDrawable()).getBitmap();
new Palette.Builder(bitmap).generate(new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
applyPalette(palette, postImageView);
}
});
/*Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
applyPalette(palette, postImageView);
}
});*/
}
#Override
public void onError() {
}
});
} else {
postImageView.setVisibility(View.GONE);
}
}
#JavascriptInterface
public void resize(final float height) {
PostViewActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Trigger: " + height + " // " + (int) (height * getResources().getDisplayMetrics().density), Toast.LENGTH_LONG).show();
//post_contentHTML.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) (height * getResources().getDisplayMetrics().density)));
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
post_contentHTML.loadUrl("javascript:Asiannews.resize(document.body.getBoundingClientRect().height)");
}
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if (source == null)
return "";
int i = source.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i + 1);
}
// Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
public class URLImageParser implements Html.ImageGetter {
#SuppressWarnings("deprecation")
class URLDrawable extends BitmapDrawable {
// the drawable that you need to set, you could set the initial drawing
// with the loading image if you need to
protected Drawable drawable;
#Override
public void draw(Canvas canvas) {
// override the draw to facilitate refresh function later
if (drawable != null) {
drawable.draw(canvas);
}
}
}
class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
#Override
protected Drawable doInBackground(String... params) {
String source = params[0];
Uri uri = Uri.parse(source);
Bitmap bitmap = null;
try {
Picasso pic = new Picasso.Builder(mContext).build();
bitmap = pic.load(uri).get();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return new BitmapDrawable(mContext.getResources(), bitmap);
}
#Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight());
// change the reference of the current drawable to the result
// from the HTTP call
urlDrawable.drawable = result;
// redraw the image by invalidating the container
URLImageParser.this.mView.invalidate();
}
}
private final Context mContext;
private final View mView;
public URLImageParser(Context context, View view) {
mContext = context;
mView = view;
}
#Override
public Drawable getDrawable(String source) {
Uri uri = Uri.parse(source);
URLDrawable urlDrawable = new URLDrawable();
ImageGetterAsyncTask task = new ImageGetterAsyncTask(urlDrawable);
task.execute(source);
return urlDrawable;
}
}
#Override
protected void onStart() {
super.onStart();
GoogleAnalytics.getInstance(PostViewActivity.this).reportActivityStart(this);
}
#Override
protected void onStop() {
super.onStop();
GoogleAnalytics.getInstance(PostViewActivity.this).reportActivityStop(this);
}
}
How can I do that?
What am I doing wrong?

how to display dynamic spinner values in android

In the code below, I took two spinners. One is for brand and other for model. But data is not being displaying in spinner. It is not showing any errors but dropdown is also not shown.
Can any one help me?
What is the mistake in the code?
Java
public class HomeFragment extends Fragment {
public HomeFragment(){}
Fragment fragment = null;
String userId,companyId;
private String brandid = "3";
public static List<LeadResult.Users> list;
public static List<BrandResult.Brands> listBrands;
public static List<ModelResult.Models> listModels;
public static ArrayList<String> listBrands_String;
// public static List<BrandResult.Brands> list1;
String[] brand_name;
Spinner spinner1;
private RelativeLayout mRel_Ownview,mRel_publicview;
private LinearLayout mLin_Stock,mLin_Contact;
private TextView mTxt_OwnView,mTxt_PublicView;
private Map<String, String> BrandMap = new HashMap<String, String>();
private RangeSeekBar<Integer> seekBar;
private RangeSeekBar<Integer> seekBar1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBar actionBar=getActivity().getActionBar();
actionBar.setTitle("DEVINE MECHINES");
SharedPreferences userPreference = getActivity().getSharedPreferences("UserDate", Context.MODE_PRIVATE);
userId=userPreference.getString("MYID", null);
companyId=userPreference.getString("companyId",null);
final View rootView = inflater.inflate(R.layout.layout_ownview, container, false);
spinner1=(Spinner)rootView.findViewById(R.id.brand1);
mTxt_OwnView=(TextView) rootView.findViewById(R.id.txt_OwnView);
mTxt_PublicView =(TextView) rootView.findViewById(R.id.txt_PublicView);
mRel_Ownview=(RelativeLayout)rootView.findViewById(R.id.ownview);
mRel_publicview =(RelativeLayout)rootView.findViewById(R.id.publicview);
listBrands = new ArrayList<BrandResult.Brands>();
listBrands_String = new ArrayList<String>();
listModels = new ArrayList<ModelResult.Models>();
seekBar = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
seekBar1 = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar1.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin1);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax1);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
mTxt_OwnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_publicview.setVisibility(View.GONE);
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.text_white));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.light_blue));
mRel_Ownview.setVisibility(View.VISIBLE);
}
});
mTxt_PublicView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_Ownview.setVisibility(View.GONE);
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.text_white));
mRel_publicview.setVisibility(View.VISIBLE);
}
});
String selectedBrandId = BrandMap.get(String.valueOf(spinner1.getSelectedItem()));
// System.out.print(url);
mLin_Stock=(LinearLayout)rootView.findViewById(R.id.stock);
mLin_Stock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment =new StockFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
});
mLin_Contact =(LinearLayout)rootView.findViewById(R.id.contacts);
mLin_Contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getLead();
fragment = new ContactFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
getLead();
}
});
// add RangeSeekBar to pre-defined layout
ViewGroup layout = (ViewGroup) rootView.findViewById(R.id.layout_seek);
layout.addView(seekBar);
ViewGroup layout1 = (ViewGroup) rootView.findViewById(R.id.layout_seek1);
layout1.addView(seekBar1);
getBrands();
getModels();
return rootView;
}
private void getBrands() {
String brandjson = JSONBuilder.getJSONBrand();
String brandurl = URLBuilder.getBrandUrl();
Log.d("url", "" + brandurl);
SendToServerTaskBrand taskBrand = new SendToServerTaskBrand(getActivity());
taskBrand.execute(brandurl, brandjson);
//Log.d("brandjson", "" + brandjson);
}
private void setBrand(String brandjson)
{
ObjectMapper objectMapper_brand = new ObjectMapper();
try
{
BrandResult brandresult_object = objectMapper_brand.readValue(brandjson, BrandResult.class);
String Brand_result = brandresult_object.getRESULT();
Log.i("Brand_result","Now" + Brand_result);
if(Brand_result.equals("SUCCESS"))
{
listBrands =brandresult_object.getBRANDS();
Log.i("listbrands", "List Brands" + listBrands);
/* for(int i = 0; i < listBrands.size(); i++){
listBrands_String.add(listBrands.get(i).toString());
Log.d("string is",""+ listBrands_String);
}*/
spinner_fn();
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskBrand extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskBrand(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String Burl = params[0];
String Bjson = params[1];
String Bresult = UrlRequester.post(mContext, Burl, Bjson);
return Bresult;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setBrand(result);
Log.i("Result","Brand Result"+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void getModels() {
String model_url = URLBuilder.getModelUrl();
String model_json = JSONBuilder.getJSONModel(brandid);
Log.d("model_json", "" + model_json);
SendToServerTaskModel taskModel = new SendToServerTaskModel(getActivity());
taskModel.execute(model_url, model_json);
}
private void setModel(String json)
{
ObjectMapper objectMapperModel = new ObjectMapper();
try
{
ModelResult modelresult_object = objectMapperModel.readValue(json, ModelResult.class);
String model_result = modelresult_object.getRESULT();
Log.d("model_result","" + model_result);
if (model_result.equals("SUCCESS"))
{
listModels =modelresult_object.getMODELS();
Log.i("listmodels", " " + listModels);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskModel extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskModel(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setModel(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void spinner_fn() {
/*ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(),
listBrands_String, android.R.layout.simple_spinner_item);*/
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext()
,android.R.layout.simple_spinner_item, listBrands_String);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);
//dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.e("Position new",""+ listBrands_String.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void getLead()
{
String url = URLBuilder.getLeadUrl();
String json = JSONBuilder.getJSONLead(userId, companyId);
SendToServerTask task = new SendToServerTask(getActivity());
task.execute(url, json);
}
private void setLead(String json)
{
ObjectMapper objectMapper = new ObjectMapper();
try
{
LeadResult result_object = objectMapper.readValue(json, LeadResult.class);
String lead_result = result_object.getRESULT();
Log.d("lead_result","" + lead_result);
if (lead_result.equals("SUCCESS"))
{
list=result_object.getUSERS();
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTask extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTask(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setLead(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}

How to pass the name of the item clicked to another class

How to pass the name of the item clicked on the on list item clicked through Intent?
is this correct?
public class View_PPT_List extends ListActivity {
private final String SAMPLE_DB_NAME = "project";
private final String PPT_TABLE_NAME1 = "notes";
private final String PPT_TABLE_NAME2 = "subject";
SQLiteDatabase notesDB = null;
ArrayList<String> results = new ArrayList<String>();
public void onListItemClick(ListView l, View view, final int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, view, position, id);
Intent ins = new Intent (View_PPT_List.this,PPTActivity.class);
ins.putExtra("com.example.tinio_bolasa_project.finame",
String.valueOf(position));
startActivity(ins);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
notesDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
notesDB.execSQL("CREATE TABLE IF NOT EXISTS " +
PPT_TABLE_NAME1 +
" ( notes_ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "subjid
INTEGER, " + "pptName VARCHAR, " + "pptPath VARCHAR);");
int x1 = getIntent().getIntExtra("pos",1);
Cursor c = notesDB.rawQuery("SELECT * FROM notes WHERE "+ x1 +"=subjid", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String pptid = c.getString(c.getColumnIndex("notes_ID"));
String ppt = c.getString(c.getColumnIndex("pptName"));
results.add(pptid + ppt);
}while (c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,results));
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (notesDB != null)
notesDB.close();
}
setContentView(R.layout.activity_view__ppt__list);
Button addppt = (Button) this.findViewById(R.id.button1);
addppt.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inten = new Intent (View_PPT_List.this, Add_PPT_Activity.class);
int x = getIntent().getIntExtra("pos",1);
inten.putExtra("key", x);
startActivity(inten);
}
});
}
}
then in my PowerpointActiv
public class PPTActivity extends Activity implements
DocumentSessionStatusListener {
private PersentationView content;
private DocumentSession session;
private SlideShowNavigator navitator;
private int currentSlideNumber;
private Button prev;
private Button next;
private SeekBar scale;
String filename = getIntent().getStringExtra("com.example.tinio_bolasa_project.finame");
String filePath = Environment.getExternalStorageDirectory()
.getPath() + "/" + filename;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
copyFileToSdcard();
this.setContentView(R.layout.powerpoint_main);
this.content = (PersentationView) this.findViewById(R.id.content);
this.prev = (Button) this.findViewById(R.id.prev);
this.prev.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prev();
}
});
this.next = (Button) this.findViewById(R.id.next);
this.next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next();
}
});
this.scale = (SeekBar) this.findViewById(R.id.scale);
this.scale
.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if (progress < 1) {
progress = 1;
}
PPTActivity.this.content
.notifyScale(progress /
250.0);
}
});
try {
Context context = PPTActivity.this.getApplicationContext();
IMessageProvider msgProvider = new AndroidMessageProvider(context);
TempFileManager tmpFileManager = new TempFileManager(
new AndroidTempFileStorageProvider(context));
ISystemColorProvider sysColorProvider = new
AndroidSystemColorProvider();
session = new DocumentSessionBuilder(new File(filePath))
.setMessageProvider(msgProvider)
.setTempFileManager(tmpFileManager)
.setSystemColorProvider(sysColorProvider)
.setSessionStatusListener(this).build();
session.startSession();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStart() {
super.onStart();
this.content.setContentView(null);
}
#Override
protected void onDestroy() {
if (this.session != null) {
this.session.endSession();
}
super.onDestroy();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Toast.makeText(this,
// "(" + event.getRawX() + "," + event.getRawY() + ")",
// Toast.LENGTH_SHORT).show();
return super.onTouchEvent(event);
}
public void onSessionStarted() {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onSessionStarted",
Toast.LENGTH_SHORT).show();
}
});
}
public void onDocumentReady() {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onDocumentReady",
Toast.LENGTH_SHORT).show();
PPTActivity.this.navitator = new SlideShowNavigator(
PPTActivity.this.session.getPPTContext());
PPTActivity.this.currentSlideNumber =
PPTActivity.this.navitator
.getFirstSlideNumber() - 1;
PPTActivity.this.next();
}
});
}
public void onDocumentException(Exception e) {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onDocumentException",
Toast.LENGTH_SHORT).show();
PPTActivity.this.finish();
}
});
}
public void onSessionEnded() {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onSessionEnded",
Toast.LENGTH_SHORT).show();
}
});
}
private void navigateTo(int slideNumber) {
SlideView slideShow = this.navitator.navigateToSlide(
this.content.getGraphicsContext(), slideNumber);
this.content.setContentView(slideShow);
}
private void next() {
if (this.navitator != null) {
if (this.navitator.getFirstSlideNumber()
+ this.navitator.getSlideCount() - 1 >
this.currentSlideNumber) {
this.navigateTo(++this.currentSlideNumber);
} else {
Toast.makeText(this, "Next page",
Toast.LENGTH_SHORT).show();
}
}
}
private void prev() {
if (this.navitator != null) {
if (this.navitator.getFirstSlideNumber() < this.currentSlideNumber)
{
this.navigateTo(--this.currentSlideNumber);
} else {
Toast.makeText(this, "Pre page", Toast.LENGTH_SHORT).show();
}
}
}
private void copyFileToSdcard() throws FileNotFoundException {
File file = new File(filePath.toString());
FileInputStream inputstream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int count = 0;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filePath));
while ((count = inputstream.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
} catch (FileNotFoundException e1) {
Toast.makeText(PPTActivity.this, "Check your sdcard",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
i get error (java.runtimeExceptin: cannot instantiate activity ComponentInfo: Java.lang.nullpointerexception)..
how to pass the String name of the item :( pls help :(
This line
String nam = getIntent().getStringExtras("string");
should be
String nam = getIntent().getStringExtra("string"); // without the 's'
String nam = getIntent().getStringExtra("string"); //not getStringExtras
Because you have specified the tag (string) to get one String
You should pick up with:
String nam = getIntent().getStringExtra("string"); //without 's'

How to get Facebook Friends list in android application

I want to get Facebook friends list in my android application (friend picker not required).I have followed the the procedure describe on Facebook application development
I have also run the samples , but confused to get the friends list. your suggestions will be appreciated.
you can get friend list with this code
String returnString = null;
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("me/friends"));
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
for(int i=0;i<jArray.length();i++){
Log.i("log_tag","User Name: "+json_data.getString("name")+
", user_id: "+json_data.getString("id"));
returnString += "\n\t" + jArray.getJSONObject(i);
};
flist.setText(returnString);
progressDialog.dismiss();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
I get just name and id , if you want get different things,
public class MainActivity extends FragmentActivity implements OnClickListener {
private static final String LOGTAG = "MainActivity";
private List<GraphUser> tags;
private Button pickFriendsButton;
Button locationtoast;
private ProfilePictureView profilePictureView;// 2
private LoginButton fb_loginBtn;// loginbtn
private TextView userName, userName2, userName3, userName4, text;
private UiLifecycleHelper uiHelper;
// private Button pickFriendsButton;
Button btnlogin;
String Name;
String Id;
String lastname;
String firstname;
String getUsername;
String get_gender;
GraphPlace location;
String profileid;
String birthday;
String get_email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationtoast = (Button) findViewById(R.id.location_button);
locationtoast.setOnClickListener(this);
btnlogin = (Button) findViewById(R.id.profile_view);
btnlogin.setOnClickListener(this);
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);// 3
text = (TextView) findViewById(R.id.text);
userName = (TextView) findViewById(R.id.user_name);
fb_loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
pickFriendsButton = (Button) findViewById(R.id.add_friend);
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
pickFriendsButton.setEnabled(enableButtons);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickFriends();
}
private void onClickPickFriends() {
final FriendPickerFragment fragment = new FriendPickerFragment();
setFriendPickerListeners(fragment);
showPickerFragment(fragment);
}
private void showPickerFragment(FriendPickerFragment fragment) {
fragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> pickerFragment,
FacebookException error) {
String text = getString(R.string.exception,
error.getMessage());
Toast toast = Toast.makeText(MainActivity.this, text,
Toast.LENGTH_SHORT);
toast.show();
}
});
}
private void setFriendPickerListeners(
final FriendPickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new FriendPickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(
PickerFragment<?> pickerFragment) {
onFriendPickerDone(fragment);
}
});
}
private void onFriendPickerDone(FriendPickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String results = "";
List<GraphUser> selection = fragment.getSelection();
tags = selection;
if (selection != null && selection.size() > 0) {
ArrayList<String> names = new ArrayList<String>();
for (GraphUser user : selection) {
names.add(user.getName());
}
results = TextUtils.join(", ", names);
} else {
results = getString(R.string.no_friends_selected);
}
// showAlert("fghjklkbvbn", results);
showAlert(getString(R.string.you_picked), results);
}
private void showAlert(String title, String message) {
new AlertDialog.Builder(MainActivity.this).setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, null).show();
}
});
fb_loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
// Intent intent = new Intent(this, ValuesShow.class);
// startActivity(i);
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
profilePictureView.setProfileId(user.getId());// 4
userName.setText("Hello , " + user.getName()
+ "\n you logged In Uaar Alumni ");
// userName2.setText("frstname"+ user.getFirstName());
// userName3.setText("address"+user.getBirthday());
// userName4.setText("texr"+user.getLocation());
get_email = (String) user.getProperty("email");
Name = user.getName();
Id = user.getId();
lastname = user.getLastName();
firstname = user.getFirstName();
getUsername = user.getUsername();
location = user.getLocation();
get_gender = (String) user.getProperty("gender");
// birthday=user.getBirthday();
// profileid=user.getId();
// profilePictureView.setProfileId(Id.getId());
// text.setText(Name + " \n " + Id + "\n" + firstname +
// "\n"
// + lastname + "\n" + getUsername + "\n" + get_gender);
// profilePicture=user.getId();
} else {
userName.setText("You are not logged");
}
}
});
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.d("FacebookSampleActivity", "Facebook session opened");
} else if (state.isClosed()) {
text.setText("");
Log.d("FacebookSampleActivity", "Facebook session closed");
}
}
};
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = null;
switch (v.getId()) {
// case R.id.fb_login_button:
case R.id.location_button:
i = new Intent(this, LocationGet.class);
break;
// i=new Intent (this,Main_menu.class);
// break;
case R.id.profile_view:
i = new Intent(this, ValuesShow.class);
Log.d(Name, "" + Name);
i.putExtra("Name", Name);
i.putExtra("get_gender", get_gender);
i.putExtra("lastname", lastname);
i.putExtra("firstname", firstname);
i.putExtra("Id", Id);
i.putExtra("birthday", birthday);
i.putExtra("get_email", get_email);
// i.putExtra("profileid",profileid);
break;
}
// profilePictureView.setProfileId(user.getId());
// Intent intent = new Intent(this, ValuesShow.class);
// intent.getBooleanExtra("location", location);
Log.d(lastname, "" + lastname);
Log.d(get_gender, "" + get_gender);
// Log.d(LOGTAG,"Name value name....");
startActivity(i);
}
}

When I press backspace did the AutoCompleteTextView show the suggestion list

My code is following ...
public class NameListActivity extends Activity implements TextWatcher {
private Button add = null;
private AutoCompleteTextView editAuto = null;
private Button chfrlist = null;
private ImageView im = null;
String access_token = new String();
private ImageView infobtn = null;
private PopupWindow popupWindow;
private View view;
private ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_name_list);
access_token = MainService.readToken();
add = (Button) findViewById(R.id.add_button);
editAuto = (AutoCompleteTextView) findViewById(R.id.editAuto);
chfrlist = (Button) findViewById(R.id.chfrlistbutton);
im = (ImageView) findViewById(R.id.helpact);
im.setOnClickListener(new ImageListener());
infobtn = (ImageView) findViewById(R.id.informbtn);
initPopupWindow();
infobtn.setOnClickListener(new infobtnListener());
editAuto.addTextChangedListener(this);
add.setOnClickListener(new addListener());
chfrlist.setOnClickListener(new ChfrListListener());
}
public class addListener implements OnClickListener {
public void onClick(View v) {
addTask task = new addTask();
task.execute();
editAuto.setText("");
}
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
onTextChangedTask task = new onTextChangedTask();
task.execute();
}
public class onTextChangedTask extends AsyncTask<Void, Void, Void> {
ArrayAdapter<String> adapter = null;
String[] userName = null;
String q = null;
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
ArrayList<String> userNameArrayList = new ArrayList<String>();
Weibo weibo = new Weibo();
#Override
protected void onPreExecute() {
weibo.setToken(access_token);
q = editAuto.getText().toString();
System.out.println("start onTextChanged");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (q.length() != 0) {
System.out.println("q is " + q);
String s1 = "https://api.weibo.com/search/suggestions/users.json";
try {
jsonArray = Weibo.client.get(s1,
new PostParameter[] { new PostParameter("q", q) })
.asJSONArray();
} catch (Throwable e) {
System.out.println("这里有个神马异常呢 。。。" + e);
}
System.out.println("return length is " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
try {
jsonObject = jsonArray.getJSONObject(i);
String sname = jsonObject.getString("screen_name");
userNameArrayList.add(sname);
} catch (JSONException e) {
e.printStackTrace();
}
}
userName = (String[]) userNameArrayList
.toArray(new String[userNameArrayList.size()]);
adapter = new ArrayAdapter<String>(NameListActivity.this,
android.R.layout.simple_dropdown_item_1line, userName);
}
return null;
}
#Override
protected void onPostExecute(Void v) {
System.out.println("post");
editAuto.setAdapter(adapter);
}
}
void showToast(String s) {
Toast toast = Toast.makeText(getApplicationContext(), s,
Toast.LENGTH_LONG);
toast.show();
}
public class addTask extends AsyncTask<Void, Void, Void> {
String s = null;
boolean flag = false;
User user = null;
Weibo weibo = new Weibo();
String screen_name = null;
protected void onPreExecute() {
Toast tt = Toast.makeText(getApplicationContext(), "正在将用户添加到备份名单",
Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER, 0, 0);
tt.show();
weibo.setToken(access_token);
screen_name = editAuto.getText().toString();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (screen_name.length() != 0) {
Users um = new Users();
try {
user = new User(Weibo.client.get(
"https://api.weibo.com/users/show.json",
new PostParameter[] { new PostParameter(
"screen_name", screen_name) })
.asJSONObject());
} catch (Throwable e) {
e.printStackTrace();
flag = true;
s = new String("您输入的这个用户好像不存在唉");
}
if (user != null) {
ContentValues values = new ContentValues();
values.put("uid", user.getId());
values.put("user_name", user.getName());
SQLiteDatabase db = null;
try {
db = MainService.getDatabase();
} catch (Exception e) {
System.out.println("db error");
finish();
}
Cursor result = db.query("users", new String[] { "uid",
"user_name" }, "uid=?",
new String[] { user.getId() }, null, null, null);
if (result.getCount() == 0)
db.insert("users", null, values);
} else {
flag = true;
s = new String("网络存在问题,检查一下吧");
}
} else {
flag = true;
s = new String("框里输入点东西才能添加啊");
}
return null;
}
#Override
protected void onPostExecute(Void v) {
if (flag == true) {
System.out.println("要打印的是" + s);
showToast(s);
}
}
}
public class infobtnListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("点击了图片");
ColorDrawable cd = new ColorDrawable(-0000);
popupWindow.setBackgroundDrawable(cd);
// popupWindow.showAsDropDown(v);
popupWindow.showAtLocation(findViewById(R.id.informbtn),
Gravity.LEFT | Gravity.BOTTOM, 0, 100);
}
}
public class ImageListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent t = new Intent(NameListActivity.this,
// GridLayoutActivity.class);
// startActivity(t);
finish();
}
}
public class ChfrListListener implements OnClickListener {
public void onClick(View v) {
if ((haveInternet() == true)
&& (GridLayoutActivity.hasAccessToken() == true)) {
// TODO Auto-generated method stub
pd = ProgressDialog.show(NameListActivity.this, "",
"正在从服务器上获取数据,可能需要较长时间,请耐心等待 ...");
/* 开启一个新线程,在新线程里执行耗时的方法 */
new Thread(new Runnable() {
public void run() {
Intent t = new Intent(NameListActivity.this,
ChooseFromListActivity.class);
startActivity(t);
finish();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();
} else {
Intent t = new Intent(NameListActivity.this,
WebViewActivity.class);
startActivity(t);
finish();
}
}
}
private void initPopupWindow() {
view = getLayoutInflater().inflate(R.layout.namewindow, null);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// 这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。
popupWindow.setOutsideTouchable(true);// 不能在没有焦点的时候使用
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
pd.dismiss();// 关闭ProgressDialog
}
};
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_name_list, menu);
return true;
}
}
My question is : when I input words in the EditText, nothing happened. But when I press backspace did the AutoCompleteTextView show the suggestion list ... the problem is in the editAuto.setAdapter(adapter);
What is wrong?
make the following changes in your code
1) Instead of
private AutoCompleteTextView editAuto = null; JUST WRITE private AutoCompleteTextView editAuto;
2) Add this line to onCrate()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, <your array name here>);
and remove this line from onTextChangedTask()
ArrayList<String> userNameArrayList = new ArrayList<String>();
3) Add this line to onCrate()
editAuto.setAdapter(adapter);
I know this is way late but for those who face similar problems here is the solution to show the autoCompleteTextView's drop down whenever you want i.e on button click or onTextChanged. After you set the ArrayAdapter for the autoCompleteTextView just put the following line.
autoCompleteTextView.showDropDown();

Categories

Resources