I'm trying to run a my project on the android emulator, the project doesn't have errors, the reference to Facebook SDK was added. But, when i run the application it shows a "onerror" message ..
please anyone can execute my code and tell me the problems (or) give me the solutions
MainActivity.java
package com.example.simplelogin1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Util;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
public class MainActivity extends Activity implements OnClickListener
{
ImageView button,userImage;
TextView textName;
Button btnShowAccessTokens;
ListView listv;
String FILENAME = "AndroidSSO_data";
String imageURL = "";
String name = "";
String userName = "";
String gender = "";
String _error;
String access_token;
private AsyncFacebookRunner mAsyncRunner=null;
private SharedPreferences mPrefs;
Facebook fb=null;
ArrayList<String> friends_list;
Boolean Connectiontimeout = false;
Bitmap profilePic;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String APP_ID="650535718332424"; //****************************APP_ID************************************
fb=new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(fb);
friends_list = new ArrayList<String>();
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
button=(ImageView) findViewById(R.id.login);
listv=(ListView) findViewById(R.id.listView1);
userImage = (ImageView) findViewById(R.id.imageView1);
textName = (TextView) findViewById(R.id.textView1);
button.setOnClickListener(this);
updateButtonImage();
//***************************Access Token Button*****************************************
btnShowAccessTokens.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
showAccessTokens();
}
});
}
public void showAccessTokens()
{
String access_token = fb.getAccessToken();
Toast.makeText(getApplicationContext(),"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
//***********************************************************************************
//*****************************Login and Logout Image Button*****************************
private void updateButtonImage()
{
if(fb.isSessionValid())
{
button.setImageResource(R.drawable.logout_button);
}else
{
button.setImageResource(R.drawable.login_button);
}
}
//***************************************************************************************
//**************************Login Onclick Method*****************************************
#Override
public void onClick(View v)
{
if(fb.isSessionValid())
{
//*****************Logout********************
try{
fb.logout(getApplicationContext());
updateButtonImage();
userImage.setVisibility(View.INVISIBLE);
textName.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
listv.setVisibility(View.INVISIBLE);
}catch (MalformedURLException e)
{
e.printStackTrace();
}catch (IOException e)
{
e.printStackTrace();
}
//************************************************************
}else
{
//**********************Login**********************************
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null)
{
fb.setAccessToken(access_token);
// Making show access tokens button visible
//btnShowAccessTokens.setVisibility(View.VISIBLE);
//listv.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0)
{
fb.setAccessExpires(expires);
}
{
fb.authorize(this,new String[] {"email","publish_stream"} , new DialogListener()
{
#Override
public void onFacebookError(FacebookError e)
{
Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values)
{
updateButtonImage();
// Function to handle complete event Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",fb.getAccessToken());
editor.putLong("access_expires",fb.getAccessExpires());
editor.commit();
//getting user profile
try {
JSONObject me = new JSONObject(fb.request("me"));
new getFacebookData().execute();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (JSONException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
//getting users Friend list
mAsyncRunner.request("me/friends", new FriendsRequestListener());
Toast.makeText(getApplicationContext(), "Success ", Toast.LENGTH_LONG).show();
userImage.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
btnShowAccessTokens.setVisibility(View.VISIBLE);
listv.setVisibility(View.VISIBLE);
}
#Override
public void onCancel()
{
Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show();
}
});
}
}
}
//***************************************onActivityResult********************************************
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
//***********************************getting users Friend list Function*******************************
private class FriendsRequestListener implements RequestListener
{
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state)
{
Log.v("", "FriendListRequestONComplete");
//Create a copy of the response so i can be read in the run() method.
friendData = response;
Log.v("friendData--", ""+friendData);
//Create method to run on UI thread
MainActivity.this.runOnUiThread(new Runnable()
{
public void run()
{
try
{
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
//Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
Log.v("friendArray--", ""+friendArray);
for(int i = 0; i< friendArray.length(); i++)
{
JSONObject frnd_obj = friendArray.getJSONObject(i);
friends_list.add(frnd_obj.getString("name")+"~~~"+frnd_obj.getString("id"));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1, friends_list);
listv.setAdapter(adapter);
} catch (JSONException e)
{
e.printStackTrace();
} catch (FacebookError e)
{
e.printStackTrace();
}
}
});
}
#Override
public void onIOException(IOException e, Object state)
{
}
#Override
public void onFileNotFoundException(FileNotFoundException e,Object state)
{
}
#Override
public void onMalformedURLException(MalformedURLException e,Object state)
{
}
#Override
public void onFacebookError(FacebookError e, Object state)
{
}
}
//**********************************************************************************************
//**************Async class for getting facebook data in background thread**********************
public class getFacebookData extends AsyncTask<String, Void, String>
{
ProgressDialog pd = null;
#Override
protected void onPreExecute(){
pd = ProgressDialog.show(MainActivity.this, "Please wait","Loading please wait..", true);
pd.setCancelable(true);
}
#Override
protected String doInBackground(String... params){
fbUserProfile();
return null;
}
#Override
protected void onPostExecute(String result){
pd.dismiss();
if (Connectiontimeout != true)
{
textName.setText(name);
userImage.setImageBitmap(profilePic);
} else {
Toast.makeText(MainActivity.this, "Connection Time out",Toast.LENGTH_SHORT).show();
}
}
}
//**********************************************************************************************************
//**********************getting user facebook data from facebook server****************************************
public void fbUserProfile()
{
try{
access_token = mPrefs.getString("access_token", null);
JSONObject jsonObj = null;
JSONObject jsonObjData = null;
JSONObject jsonObjUrl = null;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 50000);
HttpConnectionParams.setSoTimeout(httpParameters, 50000);
HttpClient client = new DefaultHttpClient(httpParameters);
String requestURL = "https://graph.facebook.com/me?fields=picture,id,name&access_token="+ access_token;
Log.i("Request URL:", "---" + requestURL);
HttpGet request = new HttpGet(requestURL);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String webServiceInfo = "";
while ((webServiceInfo = rd.readLine()) != null)
{
Log.i("Service Response:", "---" + webServiceInfo);
jsonObj = new JSONObject(webServiceInfo);
jsonObjData = jsonObj.getJSONObject("picture");
jsonObjUrl = jsonObjData.getJSONObject("data");
name = jsonObj.getString("name");
userName = jsonObj.getString("username");
gender = jsonObj.getString("gender");
imageURL = jsonObjUrl.getString("url");
profilePic = BitmapFactory.decodeStream((InputStream) new URL(imageURL).getContent());
}
} catch (Exception e)
{
Connectiontimeout = true;
}
}
//***********************************************************************************************************
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/login_button"/>
<Button
android:id="#+id/btn_show_access_tokens"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Token"
android:visibility="invisible" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/btn_show_access_tokens"
android:visibility="invisible">
</ListView>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/login"
android:src="#drawable/ic_launcher"
android:visibility="invisible" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/listView1"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/btn_show_access_tokens"
android:layout_toRightOf="#+id/imageView1"
android:text="Name"
android:visibility="invisible"/>
</RelativeLayout>
manifest.file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.simplelogin1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.simplelogin1.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
in my drawable folder:
login_button
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- When selected -->
<item android:drawable="#drawable/login"
android:state_selected="true" />
<!-- When not selected-->
<item android:drawable="#drawable/login_down" />
</selector>
logout_button
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- When selected -->
<item android:drawable="#drawable/logout"
android:state_selected="true" />
<!-- When not selected-->
<item android:drawable="#drawable/logout_down" />
</selector>
my logcat:
12-26 15:07:01.189: D/Facebook-WebView(8330): Webview loading URL: https://m.facebook.com/dialog/oauth?display=touch&client_id=650535718332424&scope=email%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
12-26 15:07:01.309: D/Facebook-authorize(8330): Login failed: com.facebook.android.DialogError: The connection to the server was unsuccessful.
12-26 15:07:01.329: D/Facebook-WebView(8330): Webview loading URL: https://m.facebook.com/dialog/oauth?display=touch&client_id=650535718332424&scope=email%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
please anyone can help me...
Related
I'm developing an android app that stores user input in the SQLite database. and displays it in TableLayout in android studio. Now I want to generate a CSV file from the contents of that Table Layout.
I need a button to generate the CSV file. Thanks in advance.
I'm new to StackOverflow and coding. So forgive me If my question wasn't right.
I really need this code to complete my project. Thanks in Advance.
Here is a sample complete project for reading data from Rss-provider insert to database and show on listview then in next activity create a csv file.
In the first activity wait to load data form Rss-provider after showing in list view data stored in DB, then click button to go to next activity for creating Csv list
For creating csv all columns should be separated with comma (,).
NOTICE: check in Android below 10
ManifestFile: :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hafez">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
android:minSdkVersion="30" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="RssReader"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Hafez">
<activity
android:name=".CsvMaker"
android:exported="false" />
<activity
android:name=".RssReader"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
rss_reader.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/lvRss"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="200dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/launch_csv_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Got to csv maker"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/lvRss" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
activity_csv_maker.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CsvMaker">
<Button
android:id="#+id/csv_maker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Make Csv file"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/csv_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="168dp"
android:text="Csv File address comes here after creation"
android:textColor="#000000"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="20dp"
android:text="TextView"
android:textColor="#000000"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.046"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
RssReader.java :
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class RssReader extends AppCompatActivity {
ListView lvRss;
ArrayList<String> titles;
ArrayList<String> links;
ArrayList<NewsInformation> news =new ArrayList<>();
private DatabaseHandler db;
private Button csv_launcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss_reader);
lvRss = (ListView) findViewById(R.id.lvRss);
csv_launcher = (Button)findViewById(R.id.launch_csv_activity);
csv_launcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),CsvMaker.class);
startActivity(intent);
}
});
titles = new ArrayList<String>();
links = new ArrayList<String>();
db = new DatabaseHandler(this);
if(isNetworkAvailable(this)) {
new ProcessInBackground().execute();
} else {
try {
db.open();
ArrayList<NewsInformation> news = db.getAllNews();
CustomAdapter adapter = new CustomAdapter(this,news);
lvRss.setAdapter(adapter);
db.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
public class ProcessInBackground extends AsyncTask<Integer, Void, Exception> {
ProgressDialog progressDialog = new ProgressDialog(RssReader.this);
Exception exception = null;
#Override
protected void onPreExecute() {
progressDialog.setMessage("Fetching Latest News!");
progressDialog.show();
}
#Override
protected Exception doInBackground(Integer... integers) {
try {
// rss feed site here
URL url = new URL("https://moxie.foxnews.com/feedburner/world.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(getInputStream(url));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
//// fetch every node item in RSS and create news_item list
for (int i = 0; i < nodeList.getLength(); i++) {
NewsInformation news_item = new NewsInformation();
Node node = nodeList.item(i);
Element parentItem = (Element) node;
NodeList links = parentItem.getElementsByTagName("link");
Element element_link = (Element) links.item(0);
NodeList element_link_childNodes = element_link.getChildNodes();
news_item.link = element_link_childNodes.item(0).getNodeValue();
NodeList titles = parentItem.getElementsByTagName("title");
Element element_title = (Element) titles.item(0);
NodeList element_title_childNodes = element_title.getChildNodes();
news_item.title = element_title_childNodes.item(0).getNodeValue();
NodeList pubDates = parentItem.getElementsByTagName("pubDate");
Element element_pubDate = (Element) pubDates.item(0);
NodeList element_pubDate_childNodes = element_pubDate.getChildNodes();
news_item.pubdate = element_pubDate_childNodes.item(0).getNodeValue();
NodeList description = parentItem.getElementsByTagName("description");
Element element_description = (Element) description.item(0);
if(element_description !=null){
NodeList element_description_childNodes = element_description.getChildNodes();
news_item.description = element_description_childNodes.item(0).getNodeValue();
Log.e("soheil", news_item.description+"");
} else {
news_item.description =" ";
}
NodeList image = parentItem.getElementsByTagName("media:group");
Element element_image = (Element) image.item(0);
NodeList image_content = element_image.getElementsByTagName("media:content");
Element image_content_element = (Element) image_content.item(0);
news_item.image = image_content_element.getAttribute("url");
news.add(news_item);
}
} catch (MalformedURLException e) {
exception = e;
Log.e("IMAGE:","1");
} catch (IOException e) {
exception = e;
Log.e("IMAGE:","2");
} catch (ParserConfigurationException e) {
e.printStackTrace();
Log.e("IMAGE:","3");
} catch (SAXException e) {
e.printStackTrace();
Log.e("IMAGE:","4");
}
return null;
}
#Override
protected void onPostExecute(Exception s) {
super.onPostExecute(s);
CustomAdapter adapter = new CustomAdapter(getBaseContext(),news);
lvRss.setAdapter(adapter);
try {
db.open();
for (int i = 0; i < news.size(); ++i) {
db.insertNewsInfo(news.get(i));
}
db.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
progressDialog.dismiss();
}
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
CsvMaker.java :
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteException;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class CsvMaker extends AppCompatActivity {
ArrayList<NewsInformation> news = new ArrayList<>();
private DatabaseHandler db;
Button csv_maker;
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_csv_maker);
csv_maker = (Button) findViewById(R.id.csv_maker);
txt = (TextView) findViewById(R.id.csv_address);
csv_maker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hasStoragePermission(1);
}
});
}
public void createCsv() {
db = new DatabaseHandler(this);
try {
db.open();
news = db.getAllNews();
db.close();
exportTheDB();
} catch (SQLException | IOException throwables) {
throwables.printStackTrace();
}
}
private void exportTheDB() throws IOException {
File myFile;
try {
myFile = new File(Environment.getExternalStoragePublicDirectory(""), "csvFile.csv");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("News_Description,News_Image,News_link,News_Title");
myOutWriter.append("\n");
for (int i = 0; i < news.size(); ++i) {
String description = news.get(i).description;
String image = news.get(i).image;
String link = news.get(i).link;
String title = news.get(i).title;
myOutWriter.append(description + "," + image + "," + link + "," + title);
myOutWriter.append("\n");
Log.e("soheil", description + "," + image + "," + link + "," + title);
}
myOutWriter.close();
fOut.close();
txt.setText(myFile.getAbsolutePath());
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
private void hasStoragePermission(int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
// return false;
} else {
createCsv();
// return true;
}
} else {
//return true;
createCsv();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == 1) {
createCsv();
}
}
}
}
DatabaseHandler.java :
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.sql.SQLException;
import java.util.ArrayList;
public class DatabaseHandler {
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context);
}
//methods for all table
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void clearTable(String tableName) {
database.delete( tableName, null, null);
}
//news table method
public void insertNewsInfo(NewsInformation newsInfo) {
ContentValues cv = new ContentValues();
cv.put("title" , newsInfo.title );
cv.put("link" , newsInfo.link );
cv.put("pubdate" , newsInfo.pubdate );
cv.put("description" , newsInfo.description );
cv.put("image" , newsInfo.image );
database.insert("news" , "writerName", cv);
}
public ArrayList<NewsInformation> getAllNews() {
ArrayList<NewsInformation> NewsInfoList = new ArrayList<NewsInformation>();
Cursor cursor = database.rawQuery("SELECT * FROM news" ,new String[]{});
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
NewsInformation newsInfo = new NewsInformation();
newsInfo.title = cursor.getString(0);
newsInfo.link = cursor.getString(1);
newsInfo.pubdate = cursor.getString(2);
newsInfo.description = cursor.getString(3);
newsInfo.image = cursor.getString(3);
NewsInfoList.add(newsInfo);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return NewsInfoList;
}
public String getBigBody(String completeBodyLink) {
Cursor cursor = database.rawQuery("select bigBody FROM news where completeTextLink = ?", new String[]{completeBodyLink});
cursor.moveToFirst();
String bigBody = cursor.getString(0);
cursor.close();
return bigBody;
}
}
DatabaseHelper.java:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "db_for_news";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 10);
//fdd
Log.i(TAG, "Object created.");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE news ( " +
" title TEXT , link TEXT , pubdate TEXT ,description TEXT ," +
" image TEXT );");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatabaseHelper.class.getName(), "Upgrading database from version "
+ oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("Drop table if exists news" );
onCreate(db);
}
}
NewsInformation.java (DataModel) :
public class NewsInformation
{
public String link;
public String title;
public String pubdate;
public String description;
public String image;
}
CustomAdapter.java:
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends ArrayAdapter<NewsInformation> {
public CustomAdapter(Context context, ArrayList<NewsInformation> news) {
super(context, 0, news);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NewsInformation item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
TextView title = (TextView) convertView.findViewById(R.id.item_text);
title.setText(item.title);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri uri = Uri.parse(item.link);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
});
return convertView;
}}
I have an application where I am recording audio in an activity. User has a start recording and stop recording button to do that. Once user clicks the stop recording button, it sends the recorded mp3 file to server (encoded string) and server process it and a response is received. I want to do the following tasks:
Since this process is long, I want to do this in a separate thread(preferably).
The process of sending and receiving response is to be shown using progress bar.
User should be able to navigate to other screens while he is waiting(i.e. current activity may be destroyed)
I tried using Toast messages before and after the function where I send mp3 to server. But there is no sync, sometimes msg comes early, sometime it's late. That's why a proper progress bar is required.How to do this? Can AsyncTask be used with what I want to achieve in (3). or should I use some other form of multithreading. Please help.Below is the activity
(Please ignore the indentations, I couldn't fix the code on stack-overflow:
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class RecordActivity extends AppCompatActivity {
private static final String LOG_TAG = "AudioRecordTest";
private static String msg = "default";
public final static String Result_MESSAGE = "in.innovatehub.ankita_mehta.tinyears.ResultMESSAGE";
private static final int REQUESTCODE_RECORDING = 109201;
private Button mRecorderApp = null;
private static String mFileName = "music.mp3";
private static String mFilePath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/TinyEars/"));
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private ImageButton mRecordImageButton = null;
private ImageButton mPlayImageButton = null;
boolean mStartRecording = true;
boolean mStartPlaying = true;
private Button mShowStatsButton = null;
private static final String TAG = "RecordActivity";
private Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
handler.postDelayed(this, 1);
if(mRecorder!=null) {
int maxAmplitude = mRecorder.getMaxAmplitude();
if (maxAmplitude != 0) {
// visualizerView.addAmplitude(maxAmplitude);
}
}
else{
}
}
};
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFilePath+"/"+mFileName);
mPlayer.prepare();
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
Log.i("Completion Listener", "Song Complete");
stopPlaying();
mRecordImageButton.setEnabled(true);
}
});
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
if (mPlayer != null) {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
mPlayImageButton.setImageResource(R.drawable.playicon);
// mStartPlaying = true;
} else {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
// mStartPlaying = false;
}
}
private void startRecording() {
AudioRecordTest(String.valueOf(System.currentTimeMillis()));
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(mFilePath+"/"+mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
try {
mRecorder.start();
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e(LOG_TAG, "start() failed");
}
}
private void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
mRecorder = null;
mRecordImageButton.setImageResource(R.drawable.micicon);
// mStartRecording = true;
} else {
mRecordImageButton.setImageResource(R.drawable.stopicon);
// mStartRecording = false;
}
}
public void AudioRecordTest(String text) {
boolean exists = (new File(mFilePath+"/"+mFileName)).exists();
if (!exists) {
new File(mFileName).mkdirs();
}
// mFileName += "audiorecordtest.mp3";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Log.d(TAG,"HERE IS FILE PATH"+mFilePath+"/"+mFileName);
mRecordImageButton = (ImageButton) findViewById(R.id.imageButton2);
mPlayImageButton = (ImageButton) findViewById(R.id.imageButton3);
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mRecorderApp = (Button) findViewById(R.id.recorderApp);
AudioRecordTest("00000");
mRecordImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onRecord(mStartRecording);
if (mStartRecording) {
mRecordImageButton.setImageResource(R.drawable.stopicon);
mPlayImageButton.setEnabled(false);
//setText("Stop recording");
} else {
mRecordImageButton.setImageResource(R.drawable.micicon);
mPlayImageButton.setEnabled(true);
mShowStatsButton.setEnabled(true);
mShowStatsButton.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Hold on... we are getting the results!",Toast.LENGTH_SHORT).show();
pressedSavBtn();
Toast.makeText(getApplicationContext(),"Parsing done ... now you may see the results!",Toast.LENGTH_SHORT).show();
//setText("Start recording");
}
mStartRecording = !mStartRecording;
}
});
mPlayImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onPlay(mStartPlaying);
if (mStartPlaying) {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
mRecordImageButton.setEnabled(false);
mShowStatsButton.setEnabled(false);
//setText("Stop playing");
} else {
mPlayImageButton.setImageResource(R.drawable.playicon);
mRecordImageButton.setEnabled(true);
mShowStatsButton.setEnabled(false);
//setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
});
//Calling recorder ...
mRecorderApp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
if (isAvailable(getApplicationContext(), intent)) {
startActivityForResult(intent, REQUESTCODE_RECORDING);
}
}
});
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mShowStatsButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
sendResults(msg);
}
});
}
public void pressedSavBtn(){
try {
thread.start();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
mShowStatsButton.setVisibility(View.VISIBLE);
}
}
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path = new File(mFilePath+"/");
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
//THIS IS FILE ENCODING CODE
File file = new File(mFilePath+"/"+mFileName);
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
Log.d("~~~~~~~~ Encoded: ", encoded);
writeToFile(encoded);
//THIS IS URL CONN CODE
String link = "http://192.168.50.0:9000/divide_result";
URL url = new URL(link);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Name", "StackOverFlow"));
nameValuePairs.add(new BasicNameValuePair("Date", encoded));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String sb = convertStreamToString(response.getEntity().getContent());
Log.d(TAG,"MESSAGE NOW"+sb);
Log.d(TAG, sb);
msg = sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void sendResults(String res){
Log.d(TAG, "Inside on create, Navigating to Result Screen Activity!");
Intent intent = new Intent(getApplicationContext(), ResultsScreenActivity.class);
intent.putExtra(Result_MESSAGE, res);
startActivity(intent);
}
public static boolean isAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list = mgr.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUESTCODE_RECORDING) {
if (resultCode == RESULT_OK) {
Uri audioUri = intent.getData();
// make use of this MediaStore uri
// e.g. store it somewhere
}
else {
// react meaningful to problems
}
}
else {
super.onActivityResult(requestCode,
resultCode, intent);
}
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
thread.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updater);
if(mRecorder!=null) {
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
handler.post(updater);
}
}
Also below is the layout-xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_record"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|center_horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:screenOrientation="portrait"
android:orientation="vertical"
tools:context="in.innovatehub.mobile.ankita_mehta.tinyears.RecordActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout_record"
android:orientation="vertical"
android:gravity="center">
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/micicon" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/playicon" />
<Button
android:id="#+id/showMeStats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:visibility="gone"
android:onClick="loadStats"
android:text="#string/showMeStats" />
<Button
android:id="#+id/recorderApp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:gravity="center"
android:text="#string/UseRecorderApp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loadStatsLinearLayout"
android:gravity="center"
android:visibility="gone"
android:orientation="vertical">
<TextView
android:id="#+id/loadingMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/loadingMessage"
/>
<ProgressBar
android:id="#+id/downloadProgress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
</LinearLayout>
</LinearLayout>
You can use an IntentService to upload your content to the server. By default, it runs on a seperate thread and is not activity bound. Then use a broadcast receiver to communicate the result back to any activity. You can find an example here.
For the progress bar, you can create a notification and show the progress bar there, this will not block your application's UI.
For hitting the server at you should use AsyncTask or Runnable thread, without disturb the main tread
for custome progress dialog use the following code
xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#color/color_white"
android:padding="5dp" >
<ProgressBar
android:id="#+id/layCustomContentProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/layCustomProgressHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/layCustomProgressInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
and the method
public Dialog getCustomPogressDialog(Context context, String heading, String text) {
// Declare the customer dialog
Dialog dlgProgress = new Dialog(context);
// Set no title for the dialog
dlgProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the content view to the customer_alert layout
dlgProgress.setContentView(R.layout.layout_custom_process_progress);
// Cancel the dialog when touched outside.
dlgProgress.setCanceledOnTouchOutside(false);
// Set the main heading
TextView dlgHeading = (TextView) dlgProgress.findViewById(R.id.layCustomProgressHeading);
dlgHeading.setText(heading);
// set the info
TextView dlgInfo = (TextView) dlgProgress.findViewById(R.id.layCustomProgressInfo);
dlgInfo.setText(text);
// Return the refenrece to the dialog
return dlgProgress;
}
My onclicklistener for my "LoginBtn". However that code inside that block only runs once and then doesn't run ever again. Please help me, I've tried everything. I know so because I have ran the log and it only logs out the value once and then never again.
package com.example.jj.test;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ScaleDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatDrawableManager;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.goebl.david.Webb;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "test";
boolean loginform;
Button Loginbtn;
ImageView logoIV;
String email;
String password;
String token;
EditText emailET;
EditText passwordET;
final Webb webb = Webb.create();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Loginbtn = (Button) findViewById(R.id.loginbtn);
Loginbtn.setOnClickListener(this);
logoIV = (ImageView) findViewById(R.id.logoIV);
emailET = (EditText) findViewById(R.id.emailET);
passwordET = (EditText) findViewById(R.id.passwordET);
loginform = false;
ModifyEditText();
}
public void ModifyEditText(){
Drawable drawable = getResources().getDrawable(R.mipmap.email);
drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * 0.6),
(int) (drawable.getIntrinsicHeight() * 0.6));
ScaleDrawable sd = new ScaleDrawable(drawable, 0, 40, 40);
emailET.setCompoundDrawables(null, null,sd.getDrawable(), null);
drawable = getResources().getDrawable(R.mipmap.password);
drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * 0.6),
(int) (drawable.getIntrinsicHeight() * 0.6));
sd = new ScaleDrawable(drawable, 0, 40, 40);
passwordET.setCompoundDrawables(null, null, sd.getDrawable(), null);
final Drawable d = emailET.getBackground();
final Drawable nd = d.getConstantState().newDrawable();
nd.setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
Color.parseColor("#FFFFFF"), PorterDuff.Mode.SRC_IN));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
emailET.setBackground(nd);
passwordET.setBackground(nd);
}
}
public void startAnimation() {
Loginbtn.setText("Login");
logoIV.startAnimation(AnimationUtils.loadAnimation(this, R.anim.animmovetop));
Loginbtn.startAnimation(AnimationUtils.loadAnimation(this, R.anim.animmovedown));
Animation animFadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
emailET.setAnimation(animFadeIn);
passwordET.setAnimation(animFadeIn);
emailET.setVisibility(View.VISIBLE);
passwordET.setVisibility(View.VISIBLE);
Loginbtn.setBackgroundResource(R.drawable.transparentrectangel);
loginform = true;
}
public void LoginRequest(final JSONObject id) throws Exception {
final String testurl = "http://api.dermatrax.com/api/v1/token/generate?email="+email+"&password="+password+;
new AsyncTask<Void, Void, JSONObject>() {
#Override
protected JSONObject doInBackground(Void... params) {
try {
Log.d("TEST","Sending request");
JSONObject response = webb
.post(testurl)
.body(id)
.ensureSuccess()
.readTimeout(4000)
.asJsonObject()
.getBody();
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
if (result != null) {
Log.d("TEST", result.toString());
try {
JSONObject data = result.getJSONObject("data");
token = data.get("token").toString();
Log.d("TEST", token);
if (token != null && !token.isEmpty()) {
Intent intent = new Intent(getApplicationContext(), UserData.class);
intent.putExtra("token", token);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_LONG);
}
}
}.execute().get();
//executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.loginbtn){
Log.d("TEST", "loginform is = " + loginform);
JSONObject params = new JSONObject();
if (loginform == false) {
try {
startAnimation();
//LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
} else if (loginform == true) {
email = emailET.getText().toString();
password = passwordET.getText().toString();
try {
//params.put("email", email);
//params.put("password", password);
params.put("email", "blabla#combustiongroup.com");
params.put("password", "blabla");
LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
xml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context="com.example.jj.test.MainActivity">
<RelativeLayout
android:background="#292446"
android:orientation="vertical"
android:id="#+id/midLL"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:padding="10dp"
android:layout_width="300dp"
android:gravity="center"
android:layout_height="40dp"
android:text="Go"
android:id="#+id/loginbtn"
android:textColor="#FFFFFF"
android:background="#drawable/roundbutton"
android:layout_below="#+id/logoIV"
android:layout_centerHorizontal="true" />
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/logoIV"
android:src="#mipmap/bigmatchlogo"
android:layout_width="70dp"
android:layout_height="70dp"
app:civ_border_width="2dp"
app:civ_border_color="#d6d6d6"
android:layout_alignBottom="#+id/emailET"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp" />
<EditText
android:layout_marginBottom="10dp"
android:textColorHint="#FFFFFF"
android:hint="Email"
android:visibility="invisible"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/emailET"
android:layout_marginTop="217dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:drawableRight="#mipmap/password"
android:hint="Password"
android:textColorHint="#FFFFFF"
android:visibility="invisible"
android:layout_width="300dp"
android:layout_height="50dp"
android:inputType="textPassword"
android:ems="10"
android:layout_marginTop="10dp"
android:id="#+id/passwordET"
android:layout_below="#+id/emailET"
android:layout_alignLeft="#+id/emailET"
android:layout_alignStart="#+id/emailET" />
</RelativeLayout>
</LinearLayout>
Log cat
06-15 15:49:11.898 8631-8631/com.example.jj.test D/TEST: loginform is = false
06-15 15:50:36.598 8631-8631/com.example.jj.test D/szxszxszxszxszx: spannableStringBuilder.......1
06-15 15:50:36.598 8631-8631/com.example.jj.test D/szxszxszx: setSpan start is 0,end is 0,flags is 18boolena is false
Write this code inside onCreate()...
Loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(v.getId() == R.id.loginbtn){
Log.d("TEST", "loginform is = " + loginform);
JSONObject params = new JSONObject();
if (loginform == false) {
try {
startAnimation();
//LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
} else if (loginform == true) {
email = emailET.getText().toString();
password = passwordET.getText().toString();
try {
//params.put("email", email);
//params.put("password", password);
params.put("email", "blabla#combustiongroup.com");
params.put("password", "blabla");
LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to develop a simple application for download using DownloadManager but I need to do some changes, I want to download using ProgressbarDialog so how to do.
class DownloadReceiver
if(downloader == null) return;
long completeId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
if(completeId == downloadTaskId){
Query query = new Query();
query.setFilterById(downloadTaskId);
Cursor cur = downloader.query(query);
if (cur.moveToFirst()) {
int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == cur.getInt(columnIndex)) {
//Download the task has been completed, remove
new VersionPersistent(context).clear();
String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
File apkFile = new File(Uri.parse(uriString).getPath());
Intent installIntent = new Intent();
installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.setAction(Intent.ACTION_VIEW);
installIntent.setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive");
context.startActivity(installIntent);
} else {
Toast.makeText(context, R.string.download_failure, Toast.LENGTH_SHORT).show();
}
}
cur.close();
and also
download and install
if ( latestVersion == null || !isNetworkActive() ) return;
downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Query query = new Query();
query.setFilterById(downloadTaskId);
Cursor cur = downloader.query(query);
// Download tasks already exists
if(cur.moveToNext()) return;
DownloadManager.Request task = new DownloadManager.Request(Uri.parse(latestVersion.targetUrl));
String apkName = extractName(latestVersion.targetUrl);
String title = String.format("%s - v%s", apkName,latestVersion.name);
task.setTitle(title);
task.setDescription(latestVersion.feature);
task.setVisibleInDownloadsUi(true);
task.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
task.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
downloadTaskId = downloader.enqueue(task);
Thanks :)
USE this class to show progress bar , this will give you an idea for downloading an image.
DownloadImageTask.java
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** Reference to the view which should receive the image */
private final WeakReference imageRef;
public DownloadImageTask(ImageView imageView) {
imageRef = new WeakReference(imageView);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(DownloadImageActivity.this, "Wait", "Downloading...");
}
#Override
protected Bitmap doInBackground(String... params) {
InputStream input = null;
try {
URL url = new URL(params[0]);
// We open the connection
URLConnection conection = url.openConnection();
conection.connect();
input = new BufferedInputStream(url.openStream(), 8192);
// we convert the inputStream into bitmap
bitmap = BitmapFactory.decodeStream(input);
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return bitmap;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Bitmap bitmap) {
progressDialog.dismiss();
if (isCancelled()) {
bitmap = null;
}
if (imageRef != null) {
ImageView imageView = imageRef.get();
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
} else
Toast.makeText(DownloadImageActivity.this, "Error while downloading the image!", Toast.LENGTH_LONG).show();
}
}
}
give permission in AndroidMenifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
you want using progressDialog, does that mean you don't need to download in the background ?
My solution is:
using AsyncTask
init the profressDialog before you call task.execute()
then show the dialog in onPreExecute
download file doInBackfround
update progess in onProgressUpdate
and dosomething you want when download complete in onPostExecute
you can learn AsyncTask and HttpURLConnection and IO Stream
You should use DownloadManager's
DownloadManager.query(DownloadManager.Query)
This gives you a Cursor to browse the columns COLUMN_TOTAL_SIZE_BYTES (Total size of the download in bytes) and COLUMN_BYTES_DOWNLOADED_SO_FAR (Number of bytes download so far).
With this information, you'll have the details to update the ProgressBarDialog.
Use Asynctask for this. Try this.
private class DownloadFileTask extends AsyncTask<String, Void, String> {
ProgressDialog pd;
#Override
protected String doInBackground(String... params) {
// Your File Download Code here
}
#Override
protected void onPostExecute(String result) {
pd.dismiss();
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(yourActivity.this);
pd.setMessage("Please Wait...");
pd.show();
}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
This is my working sample code. I use SeekBar instead of ProgressBar. Hope this help
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadmanager" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<SeekBar
android:id="#+id/seekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<LinearLayout
style="?android:buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal">
<Button
android:id="#+id/buttonStartDownload"
style="?android:buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="startDownload"
android:text="Start" />
<Button
android:id="#+id/buttonCancelDownload"
style="?android:buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="cancelDownload"
android:text="Cancel" />
<Button
android:id="#+id/buttonViewDownloads"
style="?android:buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="viewDownloads"
android:text="View" />
</LinearLayout>
</RelativeLayout>
MainActivity.java:
package com.example.downloadmanager;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private DownloadManager mDownloadManager;
private long mDownloadReference;
private TextView mTextView;
private SeekBar mSeekBar;
private static Cursor mCursor;
private static boolean mDownloading = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView);
mSeekBar = (SeekBar) findViewById(R.id.seekBar);
// Set filter to only when download is complete and register broadcast receiver
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, filter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void startDownload(View view) {
mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Uri Download_Uri = Uri.parse("http://192.168.0.100/files/test.txt");
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
// Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(false);
// Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("My Download");
// Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Android Data download using DownloadManager...");
// Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "test.txt");
// Enqueue a new download and same the referenceId
mDownloadReference = mDownloadManager.enqueue(request);
new Thread(new Runnable() {
#Override
public void run() {
mDownloading = true;
while (mDownloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(mDownloadReference);
mCursor = mDownloadManager.query(q);
if (mCursor != null && mCursor.getCount() > 0) {
mCursor.moveToFirst();
int bytes_downloaded = mCursor.getInt(mCursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int bytes_total = mCursor.getInt(mCursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (mCursor.getInt(mCursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
mDownloading = false;
}
final double dl_progress = ((bytes_downloaded * 100) / bytes_total);
runOnUiThread(new Runnable() {
#Override
public void run() {
mSeekBar.setProgress((int) dl_progress);
}
});
}
if (mCursor != null) {
mCursor.close();
}
}
}
}).start();
}
public void cancelDownload(View view) {
mDownloading = false;
if (mDownloadManager != null) {
mDownloadManager.remove(mDownloadReference);
}
mSeekBar.setProgress(0);
}
public void viewDownloads(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (mDownloadReference == referenceId) {
Uri uri = mDownloadManager.getUriForDownloadedFile(mDownloadReference);
if (uri != null) {
String mimeType = mDownloadManager.getMimeTypeForDownloadedFile(mDownloadReference);
File file = new File(uri.getPath());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("FileName", file.getName());
jsonObject.put("FilePath", file.getAbsolutePath());
jsonObject.put("FileSize", file.length());
jsonObject.put("MimeType", mimeType);
String msg = "Download completed! \n\n" + jsonObject.toString(5);
mTextView.setText(msg);
} catch (JSONException e) {
mTextView.setText(e.getMessage());
}
}
}
}
};
}
I want to customize the text inside the edittext of my chatting app. I want to bold the username and normal font for his message.
For example;
usernamejay: Hi This is Jay. How are you?
also make 1 space for reply after the message of usernamejay. i also want to change font color of username. Also if possible put message balloon for every message.
Example:
usernamejay: Hi This is Jay. How are you?
usernameclark: I'm Fine. Can i call you now for a meeting?
Can anyone help me how. This is the code for Java
import java.io.UnsupportedEncodingException;
import com.example.healthhelpv2.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import at.vcity.androidim.interfaces.IAppManager;
import at.vcity.androidim.services.IMService;
import at.vcity.androidim.tools.FriendController;
import at.vcity.androidim.tools.LocalStorageHandler;
import at.vcity.androidim.types.FriendInfo;
import at.vcity.androidim.types.MessageInfo;
public class Messaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
private EditText messageText;
private EditText messageHistoryText;
private Button sendMessageButton;
private IAppManager imService;
private FriendInfo friend = new FriendInfo();
private LocalStorageHandler localstoragehandler;
private Cursor dbCursor;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(Messaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging_screen); //messaging_screen);
messageHistoryText = (EditText) findViewById(R.id.messageHistory);
messageText = (EditText) findViewById(R.id.message);
messageText.requestFocus();
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
friend.userName = extras.getString(FriendInfo.USERNAME);
friend.ip = extras.getString(FriendInfo.IP);
friend.port = extras.getString(FriendInfo.PORT);
String msg = extras.getString(MessageInfo.MESSAGETEXT);
setTitle("Messaging with " + friend.userName);
// EditText friendUserName = (EditText) findViewById(R.id.friendUserName);
// friendUserName.setText(friend.userName);
localstoragehandler = new LocalStorageHandler(this);
dbCursor = localstoragehandler.get(friend.userName, IMService.USERNAME );
if (dbCursor.getCount() > 0){
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())&&noOfScorer<dbCursor.getCount())
{
noOfScorer++;
this.appendToMessageHistory(dbCursor.getString(2) , dbCursor.getString(3));
dbCursor.moveToNext();
}
}
localstoragehandler.close();
if (msg != null)
{
this.appendToMessageHistory(friend.userName , msg);
((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel((friend.userName+msg).hashCode());
}
sendMessageButton.setOnClickListener(new OnClickListener(){
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = messageText.getText();
if (message.length()>0)
{
appendToMessageHistory(imService.getUsername(), message.toString());
localstoragehandler.insert(imService.getUsername(), friend.userName, message.toString());
messageText.setText("");
Thread thread = new Thread(){
public void run() {
try {
if (imService.sendMessage(imService.getUsername(), friend.userName, message.toString()) == null)
{
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
//showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}});
messageText.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (keyCode == 66){
sendMessageButton.performClick();
return true;
}
return false;
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id)
{
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1)
{
return null;
}
else
{
return new AlertDialog.Builder(Messaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(messageReceiver);
unbindService(mConnection);
FriendController.setActiveFriend(null);
}
#Override
protected void onResume()
{
super.onResume();
bindService(new Intent(Messaging.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(IMService.TAKE_MESSAGE);
registerReceiver(messageReceiver, i);
FriendController.setActiveFriend(friend.userName);
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Bundle extra = intent.getExtras();
String username = extra.getString(MessageInfo.USERID);
String message = extra.getString(MessageInfo.MESSAGETEXT);
if (username != null && message != null)
{
if (friend.userName.equals(username)) {
appendToMessageHistory(username, message);
localstoragehandler.insert(username,imService.getUsername(), message);
}
else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(Messaging.this, username + " says '"+
message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
};
private MessageReceiver messageReceiver = new MessageReceiver();
public void appendToMessageHistory(String username, String message) {
if (username != null && message != null) {
messageHistoryText.append(username + ":\n");
messageHistoryText.append(message + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}
The XML messaging_screen
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ccbfbf"
android:orientation="vertical"
android:padding="10dip" >
<!--
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip"
android:text="Friend:"
/>
<EditText android:id="#+id/friendUserName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:singleLine="true"
android:editable="false" />
-->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip"
android:text="Messages:"/>
<EditText android:id="#+id/messageHistory"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:layout_weight="1"
android:editable="false"
android:gravity="top"
android:scrollbars="vertical"
android:scrollbarSize="10px"
/>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="4">
<EditText
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top"
android:hint="Type message here!" />
<Button android:id="#+id/sendMessageButton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="4"
android:text="Send"/>
</LinearLayout>
</LinearLayout>
Do this way Hope this works for you
EditText editText = (EditText)findViewById(R.id.editText);
String userName = "usernamejay";
String message = "Hi This is Jay. How are you?";
String finalStr = "<b>"+userName+":</b> "+message+"";
editText.setText(Html.fromHtml(finalStr));
On Android you can use HTML to style the text inside a TextView, see here http://daniel-codes.blogspot.pt/2011/04/html-in-textviews.html
You could also use a spannable string, may be you could look at a portion of the code in this answer.
A code extract from the link
final SpannableString out0 = new SpannableString(source[position]);
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
out0.setSpan(boldSpan, 6, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.tv.setText(out0);
P.S: but please read the solution in the link before you start applying things in your code.