How to store EditText data when sent [duplicate] - android

This question already has an answer here:
What is the simplest way in Android to keep an objects value after every app run?
(1 answer)
Closed 7 years ago.
I have an android chat application that sends messages from client to server but I am looking for a way to store the send messages in some way, other than being displayed in the list.
Here is part of my application;
public class AndroidChatApplicationActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
// msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
Button twitterButton = (Button) findViewById(R.id.website_Button);
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendToWebsite();
}
});
}
protected void sendToWebsite() {
String url = "https://www.ljmu.ac.uk/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
// receiveMsg();
// ----------------------------
// server msg receieve
// -----------------------
// End Receive msg from server//
public void sendMessageToServer(String str) {
final String str1 = str;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// String host = "opuntia.cs.utep.edu";
String host = "10.0.2.2";
String host2 = "127.0.0.1";
PrintWriter out;
try {
Socket socket = new Socket(host, 8008);
out = new PrintWriter(socket.getOutputStream());
// out.println("hello");
out.println(str1);
Log.d("", "test");
out.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test3");
}
}
}).start();
}
public void receiveMsg() {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// final String host="opuntia.cs.utep.edu";
final String host = "10.0.2.2";
// final String host="localhost";
Socket socket = null;
BufferedReader in = null;
try {
socket = new Socket(host, 8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
String msg = null;
try {
msg = in.readLine();
Log.d("", "MSGGG: " + msg);
// msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (msg == null) {
break;
} else {
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg) {
final String mssg = msg;
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.d("", "Hi Test");
}
});
}
}
Could anyone suggest a method of storing the messages other than displaying them in a list?

You can try storing them in SharedPreferences. By what I gather, you want store the input so that you can later look at then in a different activity. Have a look at SharedPreferences here http://developer.android.com/reference/android/content/SharedPreferences.html

Related

how to repeate sending value by socket

I have this client and server communication program. I got the idea from Android-er website.
This codes send a one random number when the customer pressing the connection button and I want to send new random number of every five minutes when the client had been connected with server.
Client code:
public class MainActivity extends AppCompatActivity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
textResponse.setText("");
}});
}
View.OnClickListener buttonConnectOnClickListener = new View.OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
and this is the code of server:
public class MainActivity extends AppCompatActivity {
TextView info, infoip, msg, randGen;
String message = "";
ServerSocket serverSocket;
String vRand="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
randGen= (TextView)findViewById(R.id.viewRand);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public String rGenerate() {
Random rand= new Random();
int number= rand.nextInt(500-251)+251;
vRand = String.valueOf(number);
//randGen.setText(vRand);
return vRand;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String num =rGenerate();
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(num);
printStream.close();
message += num + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
You can use handler to perform tasks at specific delay. I assumed you know how to send the random numbers using sockets so i wont mess socket codes
Button button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
sendData();
handler.postDelayed(this, 15000);
}
}, 15000);
}
});
private void sendData(){
new Worker().execute();
}
private class Worker extends AsyncTask<Void, Void, String>{
private static final String TAG = "Worker";
#Override
protected String doInBackground(Void... params) {
return "Hello There";
}
#Override
protected void onPostExecute(String s) {
Log.i(TAG, s);
}
}
You can use a Handler to do something in a certain time period. Try this
Handler customHandler = new android.os.Handler();
static final int SOCKET_VERIFY_TIME = 5000; //milliseconds
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
customHandler.postDelayed(updateTimerThread, SOCKET_VERIFY_TIME);
...
}
private Runnable updateTimerThread = new Runnable() {
public void run()
{
if(socket != null) {
if(socket.connected()) {
socket.emit("eventNumber", randNumber);
}
}
customHandler.postDelayed(this, SOCKET_VERIFY_TIME);
}
};
if you want stop updates use this
customHandler.removeCallbacks(updateTimerThread);
In your Client
public class MainActivity extends AppCompatActivity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
Handler customHandler = new android.os.Handler();
static final int SOCKET_VERIFY_TIME = 5000; //milliseconds
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
textResponse.setText("");
}});
/***** Events Socket ***********/
socket = IO.socket(new URI(URL_SERVER));
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
yourActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// Socket is connect. Do something here
/******************* Set Handler delay ******************/
customHandler.postDelayed(updateTimerThread, SOCKET_VERIFY_TIME);
/************************************************/
}
});
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// Socket is disconnect. Do something here
customHandler.removeCallbacks(updateTimerThread); // stop handler updates
}
});
}
})
}
View.OnClickListener buttonConnectOnClickListener = new View.OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
private Runnable updateTimerThread = new Runnable() {
public void run()
{
if(socket != null) {
if(socket.connected()) {
socket.emit("eventNumber", randNumber);
}
}
customHandler.postDelayed(this, SOCKET_VERIFY_TIME);
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}

Use Oauth to call yahoo api in android

I want to use the Yahoo API to get login user's email in Android. I already have got access token and user GUID, but the next step to get user email is not working.
I got the following response message:
{oauth=WWW-Authenticate: OAuth oauth_problem="OST_OAUTH_SIGNATURE_INVALID_ERROR", realm="yahooapis.com"}
My code can be found here and the problem is documented here at line 179.
Please help me to resolve this issue.
I got an answer
Full Code :
public class YahooScreen extends Activity {
private static final String REQUEST_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_request_token";
private static final String AUTHORIZE_WEBSITE_URL ="https://api.login.yahoo.com/oauth/v2/request_auth";
private static final String ACCESS_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_token";
static final String YAHOO_CALLBACK_URL = "YOUR_YAHOO_CALLBACK_URL";
static final String YAHOO_CONSUMER_KEY = "YOUR_YAHOO_CONSUMER_KEY";
static final String YAHOO_CONSUMER_SECRET = "YOUR_YAHOO_CONSUMER_SECRET";
private String oAuthVerifier;
CommonsHttpOAuthConsumer mainConsumer;
CommonsHttpOAuthProvider mainProvider;
private Button button1;
private OnClickListener button1_onclick = new OnClickListener()
{
public void onClick(View v)
{
new OAuthRequestTokenTask(v.getContext(),mainConsumer,mainProvider).execute();
}
};
private Button button2;
private OnClickListener button2_onclick = new OnClickListener()
{
public void onClick(View v)
{
new OAuthGetAccessTokenTask().execute();
}
};
private Button button3;
private OnClickListener button3_onclick = new OnClickListener()
{
public void onClick(View v)
{
getGUID();
}
};
private Button button4;
private OnClickListener button4_onclick = new OnClickListener()
{
public void onClick(View v)
{
showToken();
}
};
private Button button5;
private OnClickListener button5_onclick = new OnClickListener()
{
public void onClick(View v)
{
getProfile();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mainConsumer = new CommonsHttpOAuthConsumer(YAHOO_CONSUMER_KEY, YAHOO_CONSUMER_SECRET);
this.mainProvider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_ENDPOINT_URL, ACCESS_TOKEN_ENDPOINT_URL, AUTHORIZE_WEBSITE_URL);
//this.mainConsumer.setSigningStrategy(new YahooAuthorizationHeaderSigningStrategy());
// It turns out this was the missing thing to making standard Activity launch mode work
//this.mainProvider.setOAuth10a(true);
// get request
button1 = (Button) this.findViewById(R.id.button1);
button1.setOnClickListener(button1_onclick);
// access token
button2 = (Button) this.findViewById(R.id.button2);
button2.setOnClickListener(button2_onclick);
// guid
button3 = (Button) this.findViewById(R.id.button3);
button3.setOnClickListener(button3_onclick);
// show token
button4 = (Button) this.findViewById(R.id.button4);
button4.setOnClickListener(button4_onclick);
// Profile
button5 = (Button) this.findViewById(R.id.button5);
button5.setOnClickListener(button5_onclick);
}
#Override
protected void onNewIntent(Intent intent) {
Toast.makeText(getApplicationContext(), "OnNewIntent - It works!",
Toast.LENGTH_LONG).show();
Uri uriData = intent.getData();
if (uriData != null && uriData.toString().startsWith(YAHOO_CALLBACK_URL)) {
setVerifier(uriData.getQueryParameter("oauth_verifier"));
}
super.onNewIntent(intent);
}
class OAuthRequestTokenTask extends AsyncTask<Void, Void, String> {
final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
}
#Override
protected String doInBackground(Void... params) {
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer, YAHOO_CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
return url;
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
return null;
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
Log.i(TAG, "onPostExecute result : " + result);
super.onPostExecute(result);
}
}
public class OAuthGetAccessTokenTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
try {
mainProvider.retrieveAccessToken(mainConsumer, oAuthVerifier);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
showToken();
}
}
public void setVerifier(String verifier)
{
this.oAuthVerifier = verifier;
// this.webview.loadData("verifier = " + this.OAuthVerifier + "<br>", "text/html", null);
Log.d("setVerifier", verifier);
this.showToken();
}
public void showToken()
{
//Log.d("SubPlurkV2", "Token = " + mainConsumer.getToken() + " and secret = " + mainConsumer.getTokenSecret());
String str =
"verifier = " + this.oAuthVerifier + "<br>" +
"Token = " + mainConsumer.getToken() + "<br>" +
"secret = " + mainConsumer.getTokenSecret() + "<br>" +
"oauth_expires_in = " + mainProvider.getResponseParameters().getFirst("oauth_expires_in") + "<br>" +
"oauth_session_handle = " + mainProvider.getResponseParameters().getFirst("oauth_session_handle") + "<br>" +
"oauth_authorization_expires_in = " + mainProvider.getResponseParameters().getFirst("oauth_authorization_expires_in") + "<br>" +
"xoauth_yahoo_guid = " + mainProvider.getResponseParameters().getFirst("xoauth_yahoo_guid") + "<br>";
Log.i("YahooScreen", "str : " + str);
}
private void doGet(String url) {
OAuthConsumer consumer = this.mainConsumer;
final HttpGet request = new HttpGet(url);
Log.i("doGet","Requesting URL : " + url);
try {
consumer.sign(request);
Log.i("YahooScreen", "request url : " + request.getURI());
new Thread(new Runnable() {
#Override
public void run() {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute((HttpUriRequest) request);
Log.i("doGet","Statusline : " + response.getStatusLine());
InputStream data = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(data));
String responeLine;
StringBuilder responseBuilder = new StringBuilder();
while ((responeLine = bufferedReader.readLine()) != null) {
responseBuilder.append(responeLine);
}
Log.i("doGet","Response : " + responseBuilder.toString());
//return responseBuilder.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getGUID()
{
String GUID_URL="http://social.yahooapis.com/v1/me/guid?format=json";
this.doGet(GUID_URL);
}
public void getProfile()
{
String guid = mainProvider.getResponseParameters().getFirst("xoauth_yahoo_guid");
String url = "https://social.yahooapis.com/v1/user/" + guid + "/profile?format=json";
this.doGet(url);
}
}

Facebook API 3.6.0 login fails with FB app installed on phone

I am building an app, which is going to have support for facebook.I have downloaded facebook API 3.6.0
The problem is with login - if original FB app is not installed on phone, the login is going through custom dialog
and everything works Fine,but if FB app is installed, the login is going through custom dialog and automatically redirect to original FB app,
and then nothing happened.I have tested this on different phones, and always was the same problem.
I used this link to generate the hashkey.
In my facebook-sdk 3.6.0 I can't find this:
private static boolean ENABLE_LOG = false to true.
Anyone can help? login activity code here :
public class Login extends Activity {
SessionManager session;
EditText etLoginusername;
EditText etLoginPass;
String cus_email, cus_pass, cus_id, cus_mob, cus_name, cus_points, success,
fb_id, id;
Button btnLogin, btnForgotPass, btnfblogin;
ToggleButton remToggle;
int REM_STATUS;
public static Facebook fb;
SharedPreferences sp;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
btnfblogin = (Button) findViewById(R.id.Bfb);
btnfblogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// fb login code start
String APP_ID = getString(R.string.APP_ID);
fb = new Facebook(APP_ID);
sp = getPreferences(MODE_PRIVATE);
String access_token = sp.getString("access_token", null);
long expires = sp.getLong("access_expires", 0);
if (access_token != null) {
fb.setAccessToken(access_token);
}
if (expires != 0) {
fb.setAccessExpires(expires);
}
// code for generated facebook hash key
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.amar.facebookexample",
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
System.out.println("KeyHash : "
+ Base64.encodeToString(md.digest(),
Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
if (fb.isSessionValid()) {
// button logout
try {
fb.logout(getApplicationContext());
fblogin();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// button Login
fb.authorize(Login.this, new String[] { "email" },
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(Login.this, "fbError",
Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(Login.this, "OnError",
Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Editor editor = sp.edit();
editor.putString("access_token",
fb.getAccessToken());
editor.putLong("access_expires",
fb.getAccessExpires());
editor.commit();
session.save(fb, Login.this);
fblogin();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(Login.this, "Oncancel",
Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
#SuppressWarnings("deprecation")
private void fblogin() {
// TODO Auto-generated method stub
if (fb.isSessionValid()) {
JSONObject obj = null;
try {
String jsonUser = fb.request("me");
obj = Util.parseJson(jsonUser);
id = obj.optString("id");
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("fb_id", id));
String response = null;
try {
response = LoginHttpClient
.executeHttpPost(
"http://10.0.2.2/Upshot_Loyalty_Program/android_api/get_fb_id.php",
postParameters);
JSONObject json = new JSONObject(response);
JSONArray jArray = json.getJSONArray("customer");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
success = json_data.getString("success");
cus_id = json_data.getString("cus_id");
cus_name = json_data.getString("cus_name");
cus_points = json_data.getString("cus_points");
// User_List.add(json_data.getString("cus_id"));
}
} catch (Exception e) {
}
if (success.equals("1")) {
session = new SessionManager(getApplicationContext());
session.createLoginSessionRemMe(cus_id, cus_name, cus_points);
Intent i = new Intent(getApplicationContext(), Userpage1.class);
startActivity(i);
} else {
Intent i = new Intent(getApplicationContext(), Mobileno.class);
i.putExtra("fb_id", id);
startActivity(i);
}
}
}
}
This should temporarily solve it
fb.authorize(Login.this, new String[] { "email" },Facebook.FORCE_DIALOG_AUTH, new DialogListener()

Video player problems in Android

I was building a app involving a video player, i have a list view which displays a list of videos and clicking on any of those should play that video. The links i use are rstp youtube links & the video plays fine but when i click back button after the video is played & come to the list again i get Sorry video cant be played error.
Here is my video player class & the list Class:
Video Player class:
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single);
vid=(VideoView) findViewById(R.id.svid);
iv=(ImageView) findViewById(R.id.simg);
ip=(ImageView) findViewById(R.id.playimg);
t=(TextView) findViewById(R.id.textView1);
final ProgressDialog pd=new ProgressDialog(SingleItem.this);
Intent g=getIntent();
thumb=g.getStringExtra("thumb");
link=g.getStringExtra("link");
msg=g.getStringExtra("msg");
//link="rtsp://v7.cache5.c.youtube.com/CjYLENy73wIaLQmgwjdV-8ZI5BMYJCAkFEIJbXYtZ29vZ2xlSARSBWluZGV4YKSf0bH1u4jEUAw=/0/0/0/video.3gp";
String path1=link;
MediaController mc = new MediaController(this);
mc.setAnchorView(vid);
mc.setMediaPlayer(vid);
uri=Uri.parse(path1);
vid.setMediaController(mc);
vid.setVideoURI(uri);
// vid.requestFocus();
//iv.setClickable(true);
loadImage(thumb);
t.setText(msg);
ip.setClickable(true);
ip.setImageResource(R.drawable.play);
// ip.setVisibility(ImageView.INVISIBLE);
vid.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
//ip.setVisibility(ImageView.VISIBLE);
pd.dismiss();
}
});
ip.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vid.start();
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setMessage("Loading Video...");
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.show();
if(vid.isPlaying()){
iv.setVisibility(ImageView.INVISIBLE);
ip.setVisibility(ImageView.INVISIBLE);
}else{
iv.setVisibility(ImageView.VISIBLE);
ip.setVisibility(ImageView.VISIBLE);
vid.stopPlayback();
}
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
vid.stopPlayback();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
vid.stopPlayback();
}
void loadImage(String image_location){
URL imageURL = null;
try {
imageURL = new URL(image_location);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection= (HttpURLConnection)imageURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap
iv.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
My List class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pf=new PrefMethods(this);
e=(EditText) findViewById(R.id.editText1);
go=(Button) findViewById(R.id.bGo);
e.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(e.getText().length()==0){
adapter=new LazyAdapter(VideoList.this, myList);
//Toast.makeText(getApplicationContext(), "Here finally", 500).show();
list.setAdapter(adapter);
}
}
});
ArrayList<String> items = new ArrayList<String>();
myList = new ArrayList<HashMap<String, String>>();
arr_link = new ArrayList<String>();
arr_thumb = new ArrayList<String>();
arr_msg = new ArrayList<String>();
allItems=new ArrayList<HashMap<String, String>>();
try {
URL urlnew= new URL("link");
HttpURLConnection urlConnection =
(HttpURLConnection) urlnew.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// gets the server json data
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String next;
while ((next = bufferedReader.readLine()) != null){
JSONArray ja = new JSONArray(next);
int k=ja.length();
vid_id=pf.loadprefs();
//Toast.makeText(getApplicationContext(), "Here", 500).show();
for (int i = 0; i < ja.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jo = (JSONObject) ja.get(i);
WaveData waveData = new WaveData(jo.getString("VUpload"), jo.getInt("recid"),jo.getString("VYoutube"),jo.getString("VMessage"),jo.getString("VThumb"));
if(jo.getInt("recid")>vid_id){
if(i==k-1){
pf.saveprefs(jo.getInt("recid"));
//vid_id=2;
vid_id=jo.getInt("recid");
//Toast.makeText(getApplicationContext(), ""+vid_id, 500).show();
}else{}
}else{}
if(jo.has("VUpload")){
map.put("msg", jo.getString("VMessage"));
map.put("youtube", jo.getString("VYoutube"));
map.put("thumb", jo.getString("VThumb"));
// Toast.makeText(getApplicationContext(), "Here too", 500).show();
myList.add(map);
//Toast.makeText(getApplicationContext(), jo.getString("VMessage"), 500).show();
items.add(jo.getString("VMessage"));
arr_msg.add(jo.getString("VMessage"));
arr_link.add(jo.getString("VYoutube"));
arr_thumb.add(jo.getString("VThumb"));
}
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, myList);
//Toast.makeText(getApplicationContext(), "Here finally", 500).show();
list.setAdapter(adapter);
//Toast.makeText(getApplicationContext(), "Set List ", 500).show();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String l=list.getAdapter().getItem(arg2).toString();
Toast.makeText(getApplicationContext(), l, 500).show();
String sthumb=arr_thumb.get(arg2);
String slink=arr_link.get(arg2);
String smsg=arr_msg.get(arg2);
Intent vid=new Intent(getApplicationContext(), SingleItem.class);
vid.putExtra("link", slink);
vid.putExtra("msg", smsg);
vid.putExtra("thumb", sthumb);
startActivity(vid);
}
});
go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
allItems.clear();
String l= e.getText().toString();
for(int g=0;g<vid_id;g++){
if(myList.get(g).containsValue(l)){
allItems.add(myList.get(g));
}
}
adapter=new LazyAdapter(VideoList.this, allItems);
// Toast.makeText(getApplicationContext(), "Here finally", 500).show();
list.setAdapter(adapter);
}
});
}
}
The video list gets loaded no issues & even the video plays but when i click the back button it comes back to list & says Sorry,this video cant be played !
Any ideas why the error?
Thanks in advance guys !
Fixed this issue, all i did was made the video stop playing in the onPause & onDestroy method.
Now it works fine without any error

android onclick buttons to write strings on Socket

Hi I am building an app which requires the user to press buttons (total 8 buttons). These buttons used to send strings to the server onclick . The problem here I'm having is when i press any of the button after connecting to the server it sends the string as it should but the 2nd time nothing happens. I was suggested to use doInBackground() from AsyncTask, to run keep running the socket and write to it each time the buttons are pressed. But i am unable to do so. What should I do ? I don't know where is the problem. Here I'm putting my code.
This is my Activity
public class Acontroller extends Activity {
Button bForward;
Button bBackward;
Button bRight;
Button bLeft;
Button bSelect;
Button bStart;
Button bB;
Button bA;
Socket s;
DataOutputStream os;
String ip;
// MyAppActivity ip = new MyAppActivity();
MyThread start = new MyThread();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.nesskin);
bForward = (Button) findViewById(R.id.bForward);
bBackward = (Button) findViewById(R.id.bBackward);
bRight = (Button) findViewById(R.id.bRight);
bLeft = (Button) findViewById(R.id.bLeft);
bSelect = (Button) findViewById(R.id.bSelect);
bStart = (Button) findViewById(R.id.bStart);
bA = (Button) findViewById(R.id.bA);
bB = (Button) findViewById(R.id.bB);
Bundle gotIP = getIntent().getExtras();
ip = gotIP.getString("ipAddress");
// start.doInBackground(ip);
//start.execute(ip);
// sock.start();
}
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
bForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
start.execute(ip);
}
});
And from the thread.
public class MyThread extends AsyncTask <String, Void, String>{
Socket s;
DataOutputStream os;
String ip;
String cmd;
#Override
protected void onPreExecute() {
Log.i("AsyncTask", "onPreExecute");
}
#Override
protected String doInBackground(String... params) {
int port = 2222;
// TODO Auto-generated method stub
if(s.isConnected()){
try {
os.writeUTF("forward");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
s= new Socket(ip, port);
os = new DataOutputStream(s.getOutputStream());
os.writeUTF("forward");
}catch(Exception e){
e.printStackTrace();
}
finally{
if (s!= null){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (os != null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return null;
}
My objective is as many times the user clicks the buttons the respective strings must be send to the server. Here is my server code I'm using PC as server.
public class Server
public static void main(String[] args) throws AWTException {
String msg_received = null;
String fw = "forward";
String bw = "backward";
String l = "left";
String r = "right";
String se = "select";
String st = "start";
String a = "a";
String b = "b";
String fin = "finish";
// Boolean finish = (msg_received.equal(fin));
Robot robot = new Robot();
try {
ServerSocket ss = new ServerSocket(2222);
System.out.println("Server Started...");
while (true) {
Socket s = ss.accept();
System.out.println("Connection Request Received");
DataInputStream DIS = new DataInputStream(s.getInputStream());
msg_received = DIS.readUTF();
System.out.println(msg_received);
// s.close();
// ss.close();
if (msg_received.equals(fw)) {
// tu yeh kerna
robot.keyPress(KeyEvent.VK_UP);
robot.keyRelease(KeyEvent.VK_UP);
}
Please help me it really important to me. Thanks in advance.
You can't re-use an AsyncTask. You have to create a new object and call execute.
Replace
start.execute();
with
start = new MyThread();
start.execute(ip);
or if you can get away with removing the instance when it's done, then you can just do this:
(new MyThread()).start();
EDIT:
To send parameters to AsyncTask, do this:
start.execute(ip, cmd, param3, param4, param5);
in doInBackground collect the parameters like so:
protected Void doInBackground(String... params)
{
String ipParam = params[0];
String cmdParam = params[1];
String thirdParam = params[2];
String fourthParam = params[3];
String fifthParam = params[4];
}
You can pass as many Strings as you want into params and it will automatically create a new array containing all the parameters at runtime. Just note that if you only pass in two, then the params size will only be two. If you pass in 100 parameters, then params will be 100 units in size.

Categories

Resources