Save user input string to variable on button click - java

in my application the user will input a channel they want to subscribe to in an editable text field. Upon clicking the subscribe button, the variable that is placed in my method to subscribe the user should be updated to that of the users choice and then a toast will appear notifying the user that they are subscribed to this channel.
At the bottom, I get the string value that the user inputs in the EditText field, but I don't think I'm putting it in the right place. Can someone take a look at it and let me know what I'm doing wrong? Let me know if I wasn't clear or am missing something and I can try to explain better. Thanks!
public class MainActivity extends ActionBarActivity {
private Button channelSubscribeButton;
private EditText subscribeChannelEditText;
//Declare variable
String subscribeChannel = null;
//-------------------------Access PubNub API-------------------------//
Pubnub pubnub = new Pubnub("pub-c-940c4776-36ff-425f-9677-f1c904a9d57b", "sub-c-cf42b292-a8bf-11e4-85d5-0619f8945a4f");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
channelSubscribeButton = (Button) findViewById(R.id.subscribe_button);
subscribeChannelEditText = (EditText) findViewById(R.id.channel_name);
//-------------------------Subscribe to a Channel to Receive Messages-------------------------//
try {
//THIS IS WHERE I AM INPUTTING THE VARIABLE THAT CONTAINS THE USER INPUTTED TEXT//
//I AM GETTING ERROR THAT SAYS IT CAN'T RESOLVE THE SYMBOL 'subscribeChannel'//
pubnub.subscribe(subscribeChannel, new Callback() {
#Override
public void connectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : CONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void disconnectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : DISCONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
public void reconnectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : RECONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void successCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
}
#Override
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB", "SUBSCRIBE : ERROR on channel " + channel
+ " : " + error.toString());
}
}
);
} catch (PubnubException e) {
Log.d("PUBNUB", e.toString());
}
public void onChannelButtonClick(View view) {
subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
String yourSubscribeChannel = "Subscribed to the " + subscribeChannel + " Channel";
Toast.makeText(this, yourSubscribeChannel, Toast.LENGTH_LONG).show();
return subscribeChannel;
}

Your subscribeChannel variable is only visible within the scope of your onChannelButtonClick method. Declare it outside along with your instance variables.
public void onChannelButtonClick(View view) {
//here you set it and then it's lost.
String subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
String yourSubscribeChannel = "Subscribed to the " + subscribeChannel + " Channel";
Toast.makeText(this, yourSubscribeChannel, Toast.LENGTH_LONG).show();
}
Instead do:
//declare it.
String subscribeChannel = null;
And then on your method assign the value.
public void onChannelButtonClick(View view) {
//assign it.
subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
String yourSubscribeChannel = "Subscribed to the " + subscribeChannel + " Channel";
Toast.makeText(this, yourSubscribeChannel, Toast.LENGTH_LONG).show();
}

Related

How to replace downloaded image with same file name in storage from server?

I implement the function in which user can save image from the server.
Here is my code.
BasicImageDownloader imageDownloader = new BasicImageDownloader(new BasicImageDownloader.OnImageLoaderListener()
{
#Override
public void onError(BasicImageDownloader.ImageError error)
{
Toast.makeText(mContext, "Error code " + error.getErrorCode() + ": " + error.getMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onProgressChange(int percent)
{
}
#Override
public void onComplete(Bitmap result)
{
final Bitmap.CompressFormat mFormat = Bitmap.CompressFormat.JPEG;
final File myImageFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
+ "Android" + File.separator
+"data" +File.separator
+"test" +File.separator
+ "profileimage" +File.separator
+ mPost.get(i).getUid() + "." + mFormat.name().toLowerCase());
BasicImageDownloader.writeToDisk(myImageFile, result, new BasicImageDownloader.OnBitmapSaveListener() {
#Override
public void onBitmapSaved() {
Toast.makeText(mContext, "Image saved as: " + myImageFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
}
#Override
public void onBitmapSaveError(BasicImageDownloader.ImageError error) {
Toast.makeText(mContext, "Error code " + error.getErrorCode() + ": " +
error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}, mFormat, false);
}
});
imageDownloader.download("link", true);
It works great but whenever the same name exists in the storage location . It throw the exception:"file is already exists".
Now the problem is how to replace downloaded image whenever same file exists in the storage location?
I found the BasicImageDownloader class on the web.
The last parameter of writeToDisk is for overwriting.
So if you set it to true like this:
BasicImageDownloader.writeToDisk(..., true);
it should overwrite the file.

How to change Bluetooth scan interval?

I am building a collector application that continuously scans the Bluetooth and writes the RSSI results in a file, I used this code but it scans and records the data every 5-second.
I want to make it scan and collect the RSSI data every 100 mill second.Please help me to modify this.
private ScanCallback leScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, final ScanResult result) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
// Tried new Handler(Looper.myLopper()) also
#Override
public void run() {
peripheralTextView.append("MAC: " + result.getDevice().getAddress() +","
+ result.getDevice().getName() +","
+ " RSSI: " + result.getRssi() + "\n");
}
});
try {
long TimeStampMillSec = TimeStampMillSec();
String DateTimeToIso8601Datetimehhmmss = DateTimeToIso8601Datetimehhmmss();
JSONObject jsonMsg =new JSONObject();
//Edited by Mansour
jsonMsg.put("BLue",
"6"+","+phoneIMEI+","+DateTimeToIso8601Datetimehhmmss+
","+TimeStampMillSec+","+result.getDevice().getName()
+ "," + result.getRssi());
WriteMessageLog(0, jsonMsg +"\n");
// auto scroll for text view
final int scrollAmount =
peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount())
- peripheralTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
}
catch (Exception e)
{
e.printStackTrace();
}
}
};`

Calling a public Class in onClick

I have an onClick event:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPrayerTime = (Button)findViewById(R.id.muteButton);
mPrayerTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//call CityModelHere
}
});
and I want to call this class (and specifically get the fajr variable without it returning null as it does if I instantiate a new cityModel in the onClick):
public class cityModel implements Serializable {
private String fajr;
public void setFajr(String fajr) {
this.fajr= fajr;
}
public String getFajr() {
return fajr;
}
}
the class takes the string from a later class here just in case:
protected void outputTimings(JSONArray jsonArray) {
String[] prayers = {"fajr", "shurooq", "dhuhr", "asr", "maghrib", "isha"};
cityModel cityObj;
try {
cityObj= new cityModel();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject cityObject =
jsonArray.getJSONObject(i);
result = result + "fajr" + " : "
+ cityObject.getString("fajr") + "\n" + result + "shurooq" + " : "
+ cityObject.getString("shurooq") + "\n" + result + "dhuhr" + " : "
+ cityObject.getString("dhuhr") + "\n" + result + "asr" + " : "
+ cityObject.getString("asr") + "\n" + result + "maghrib" + " : "
+ cityObject.getString("maghrib") + "\n" + result + "isha" + " : "
+ cityObject.getString("isha") + "\n";
cityObj.setFajr(""+cityObject.getString("fajr"));
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
Make your variable final, and then you can access it from the setOnClickListener.

How to call a Method in OnClickListener without variable (Fajr) in the method becoming null when called

In my OnClickListener:
private Button mPrayerTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPrayerTime = (Button)findViewById(R.id.muteButton);
mPrayerTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cityModel cityObj= new cityModel();
String fajr=cityObj.getFajr();
Log.d("Fajr", ""+fajr);
}
});
}
I call a method called cityModel, found here
public final class cityModel implements Serializable {
private String fajr;
public void setFajr(String fajr) {
this.fajr= fajr;
}
public String getFajr() {
return fajr;
}
}
which retrieves set.Fajr from:
protected void outputTimings(JSONArray jsonArray) {
String[] prayers = {"fajr", "shurooq", "dhuhr", "asr", "maghrib", "isha"};
final cityModel cityObj;
try {
cityObj= new cityModel();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject cityObject =
jsonArray.getJSONObject(i);
result = result + "fajr" + " : "
+ cityObject.getString("fajr") + "\n" + result + "shurooq" + " : "
+ cityObject.getString("shurooq") + "\n" + result + "dhuhr" + " : "
+ cityObject.getString("dhuhr") + "\n" + result + "asr" + " : "
+ cityObject.getString("asr") + "\n" + result + "maghrib" + " : "
+ cityObject.getString("maghrib") + "\n" + result + "isha" + " : "
+ cityObject.getString("isha") + "\n";
cityObj.setFajr(""+cityObject.getString("fajr"));
}
When I tried to debug, I found that cityModel finds the value for fajr and stores it just fine, so the issue seems to be with how I call the method because whenever I look for the label Fajr in logcat it shows up as null.

Stream API in twitter Not responding

I am using twitter4j Stream API 3.0.3 jar. I tried to get the User Stream and tweets my code is given below. It is running only not showing any outputs for past 1 hour.
public class StreamAPI {
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("xxxx");
cb.setOAuthConsumerSecret("xxxx");
cb.setOAuthAccessToken("xxx-x");
cb.setOAuthAccessTokenSecret("xxxxx");
cb.setUseSSL(true);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
RawStreamListener listener = new RawStreamListener() {
#Override
public void onMessage(String rawJSON) {
System.out.println(rawJSON);
}
#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
twitterStream.addListener(listener);
twitterStream.sample();
}
}
and when I try to get user, it shows 401 Authentication error
static UserStreamListener listener = new UserStreamListener() {
#Override
public void onStatus(Status status) {
System.out.println("onStatus #" + status.getUser().getScreenName() + " - " + status.getText());
}
#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
#Override
public void onDeletionNotice(long directMessageId, long userId) {
System.out.println("Got a direct message deletion notice id:" + directMessageId);
}
#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got a track limitation notice:" + numberOfLimitedStatuses);
}
#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
#Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
#Override
public void onFriendList(long[] friendIds) {
System.out.print("onFriendList");
for (long friendId : friendIds) {
System.out.print(" " + friendId);
}
System.out.println();
}
#Override
public void onFavorite(User source, User target, Status favoritedStatus) {
System.out.println("onFavorite source:#"
+ source.getScreenName() + " target:#"
+ target.getScreenName() + " #"
+ favoritedStatus.getUser().getScreenName() + " - "
+ favoritedStatus.getText());
}
#Override
public void onUnfavorite(User source, User target, Status unfavoritedStatus) {
System.out.println("onUnFavorite source:#"
+ source.getScreenName() + " target:#"
+ target.getScreenName() + " #"
+ unfavoritedStatus.getUser().getScreenName()
+ " - " + unfavoritedStatus.getText());
}
#Override
public void onFollow(User source, User followedUser) {
System.out.println("onFollow source:#"
+ source.getScreenName() + " target:#"
+ followedUser.getScreenName());
}
#Override
public void onDirectMessage(DirectMessage directMessage) {
System.out.println("onDirectMessage text:"
+ directMessage.getText());
}
#Override
public void onUserListMemberAddition(User addedMember, User listOwner, UserList list) {
System.out.println("onUserListMemberAddition added member:#"
+ addedMember.getScreenName()
+ " listOwner:#" + listOwner.getScreenName()
+ " list:" + list.getName());
}
#Override
public void onUserListMemberDeletion(User deletedMember, User listOwner, UserList list) {
System.out.println("onUserListMemberDeleted deleted member:#"
+ deletedMember.getScreenName()
+ " listOwner:#" + listOwner.getScreenName()
+ " list:" + list.getName());
}
#Override
public void onUserListSubscription(User subscriber, User listOwner, UserList list) {
System.out.println("onUserListSubscribed subscriber:#"
+ subscriber.getScreenName()
+ " listOwner:#" + listOwner.getScreenName()
+ " list:" + list.getName());
}
#Override
public void onUserListUnsubscription(User subscriber, User listOwner, UserList list) {
System.out.println("onUserListUnsubscribed subscriber:#"
+ subscriber.getScreenName()
+ " listOwner:#" + listOwner.getScreenName()
+ " list:" + list.getName());
}
#Override
public void onUserListCreation(User listOwner, UserList list) {
System.out.println("onUserListCreated listOwner:#"
+ listOwner.getScreenName()
+ " list:" + list.getName());
}
#Override
public void onUserListUpdate(User listOwner, UserList list) {
System.out.println("onUserListUpdated listOwner:#"
+ listOwner.getScreenName()
+ " list:" + list.getName());
}
#Override
public void onUserListDeletion(User listOwner, UserList list) {
System.out.println("onUserListDestroyed listOwner:#"
+ listOwner.getScreenName()
+ " list:" + list.getName());
}
#Override
public void onUserProfileUpdate(User updatedUser) {
System.out.println("onUserProfileUpdated user:#" + updatedUser.getScreenName());
}
#Override
public void onBlock(User source, User blockedUser) {
System.out.println("onBlock source:#" + source.getScreenName()
+ " target:#" + blockedUser.getScreenName());
}
#Override
public void onUnblock(User source, User unblockedUser) {
System.out.println("onUnblock source:#" + source.getScreenName()
+ " target:#" + unblockedUser.getScreenName());
}
#Override
public void onException(Exception ex) {
ex.printStackTrace();
System.out.println("onException:" + ex.getMessage());
}
};
Is anyone can help me to get details about the user, users followers following and tweets in Twitter
The 401 error code indicates that you're not properly authenticated. Are you certain those credentials are correct?
A good way to test that would be to connect to the regular streaming API (rather than a user stream) and seeing if you still get a 401. If you do, then your credentials are incorrect. If it works, then there's a problem with the user stream you're requesting.

Categories

Resources