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'
Related
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
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?
I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}
I created a class called FTPSite with getters and setters for name,address,username,password,port,passive mode. I'm trying to create site manager by using a custom adapter to show the site names however I'm just getting the package name and numbers as my list item.
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText sitename;
public EditText address;
public EditText username;
public EditText password;
public EditText port;
public CheckBox passive;
public ListView site_list;
public TextView tview;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
boolean _passive;
List<FTPSite> model = new ArrayList<FTPSite>();
SiteAdapter adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter();
site_list.setAdapter(adapter);
sitename = (EditText) findViewById(R.id.dialogsitename);
address = (EditText) findViewById(R.id.dialogaddress);
username = (EditText) findViewById(R.id.dialogusername);
password = (EditText) findViewById(R.id.dialogpassword);
port = (EditText) findViewById(R.id.dialogport);
passive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
siteManager();
}
});
savesite = (Button) findViewById(R.id.saveSite);
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
siteManager();
}
});
openDb();
displayRecords();
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void siteManager() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = sitename.getText().toString();
_address = address.getText().toString();
_username = username.getText().toString();
_password = password.getText().toString();
_port = Integer.parseInt(port.getText().toString());
_passive = false;
if (passive.isChecked()) {
_passive = true;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = sitename.getText().toString();
_address = address.getText().toString();
_username = username.getText().toString();
_password = password.getText().toString();
_port = Integer.parseInt(port.getText().toString());
long newId = myDb.insertRow(_name, _address, _username,
_password, 21);
FTPSite tmpSite = new FTPSite();
tmpSite.setName(_name);
tmpSite.setAddress(_address);
tmpSite.setUsername(_username);
tmpSite.setPassword(_password);
tmpSite.setPort(_port);
model.add(tmpSite);
adapter.notifyDataSetChanged();
Toast.makeText(SiteManager.this, tmpSite.getName(),
Toast.LENGTH_SHORT).show(); // Shows the correct name
// displayRecords();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
// displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
String msg = "";
if (c.moveToFirst()) {
do {
int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
msg += "id=" + id + "\n";
msg += ", name=" + _name + "\n";
msg += ", address=" + _address + "\n";
msg += ", username=" + _username + "\n";
msg += ", password=" + _password + "\n";
msg += ", port=" + _port + "\n";
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
public SiteAdapter(Context context, int resource, int textViewResourceId, List<T> objects) {
super(context,resource,textViewResourceId,objects);
}
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.siterow, null);
}
FTPSite s = model.get(position);
((TextView) row.findViewById(R.id.title)).setText(s.getName());
return (row);
}
}
FTPSite.java
public class FTPSite {
private String name = "";
private String address = "";
private String username = "";
private String password = "";
private int port = 21;
private boolean passive = false;
public FTPSite() {
// TODO Auto-generated constructor stub
}
public String getName() {
return (name);
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return (address);
}
public void setAddress(String address) {
this.address = address;
}
public String getUsername() {
return (username);
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return (password);
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return (port);
}
public void setPort(int port) {
this.port = port;
}
public boolean isPassive() {
return (passive);
}
public void setPassive(boolean passive) {
this.passive = passive;
}
}
And my siterow.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:minHeight="?android:attr/listPreferredItemHeight"
/>
EDIT
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(SiteManager.this, R.layout.siterow,
R.id.title, model);
site_list.setAdapter(adapter);
sitename = (EditText) findViewById(R.id.dialogsitename);
address = (EditText) findViewById(R.id.dialogaddress);
username = (EditText) findViewById(R.id.dialogusername);
password = (EditText) findViewById(R.id.dialogpassword);
port = (EditText) findViewById(R.id.dialogport);
passive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
siteManager();
}
});
savesite = (Button) findViewById(R.id.saveSite);
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
siteManager();
}
});
openDb();
displayRecords();
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void siteManager() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = sitename.getText().toString();
_address = address.getText().toString();
_username = username.getText().toString();
_password = password.getText().toString();
_port = Integer.parseInt(port.getText().toString());
_passive = false;
if (passive.isChecked()) {
_passive = true;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = sitename.getText().toString();
_address = address.getText().toString();
_username = username.getText().toString();
_password = password.getText().toString();
_port = Integer.parseInt(port.getText().toString());
long newId = myDb.insertRow(_name, _address, _username,
_password, 21);
FTPSite tmpSite = new FTPSite();
tmpSite.setName(_name);
tmpSite.setAddress(_address);
tmpSite.setUsername(_username);
tmpSite.setPassword(_password);
tmpSite.setPort(_port);
model.add(tmpSite);
adapter.notifyDataSetChanged();
Toast.makeText(SiteManager.this, tmpSite.getName(),
Toast.LENGTH_SHORT).show();
// displayRecords();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, resource, textViewResourceId, objects);
}
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.siterow, null);
}
FTPSite s = model.get(position);
((TextView) row.findViewById(R.id.title)).setText(s.getName());
return (row);
}
replace SiteAdapter adapter;
with
ArrayAdapter<FTPSite> adapter
then in your adapter class you need to create a constructor like this
public SiteAdapter(Context context, int resource, int textViewResourceId, List<T> objects) {
super(context,resource,textViewResourceId,objects);
}
see documentation
EDIT:
when you declare you need to do
adapter = new SiteAdapter(this,r.layout.your_layout,new int[] {r.id.title},model);
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();