Event not saved in Calendar - java

I want to save an event in the calendar directly, without openning the calendar app. I have found that in some devices the event is not saved in calendar, but I am not getting any error in the logcat. This is the code that I am using,
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues()
values.put(CalendarContract.Events.DTSTART, DateBuilder.getStartDayCalendar());
values.put(CalendarContract.Events.DTEND, DateBuilder.getEndDayCalendar());
values.put(CalendarContract.Events.TITLE, "Title");
values.put(CalendarContract.Events.DESCRIPTION, "description");
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
Does anyone know what is happening?
Thanks!
UPDATE
In same devices you need to set up the status,Events.STATUS, Events.STATUS_CONFIRMED, that was the problem

Find the solution :
Follow the steps it will create event directly :
Manifest.xml
Add permissions in Manifest
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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="testpreference.com.testcalendar.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calendars" />
<Spinner
android:id="#+id/calendarid_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/newevent_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Event"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Spinner calendarIdSpinner;
private Hashtable<String,String> calendarIdTable;
private Button newEventButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendarIdSpinner = (Spinner) findViewById(R.id.calendarid_spinner);
newEventButton = (Button) findViewById(R.id.newevent_button);
newEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CalendarHelper.haveCalendarReadWritePermissions(MainActivity.this))
{
addNewEvent();
}
else
{
CalendarHelper.requestCalendarReadWritePermission(MainActivity.this);
}
}
});
calendarIdSpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
if (CalendarHelper.haveCalendarReadWritePermissions(this))
{
//Load calendars
calendarIdTable = CalendarHelper.listCalendarId(this);
updateCalendarIdSpinner();
}
}
private void updateCalendarIdSpinner()
{
if (calendarIdTable==null)
{
return;
}
List<String> list = new ArrayList<String>();
Enumeration e = calendarIdTable.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
list.add(key);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
calendarIdSpinner.setAdapter(dataAdapter);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode==CalendarHelper.CALENDARHELPER_PERMISSION_REQUEST_CODE)
{
if (CalendarHelper.haveCalendarReadWritePermissions(this))
{
Toast.makeText(this, (String)"Have Calendar Read/Write Permission.",
Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void addNewEvent()
{
if (calendarIdTable==null)
{
Toast.makeText(this, (String)"No calendars found. Please ensure at least one google account has been added.",
Toast.LENGTH_LONG).show();
//Load calendars
calendarIdTable = CalendarHelper.listCalendarId(this);
updateCalendarIdSpinner();
return;
}
final long oneHour = 1000 * 60 * 60;
final long tenMinutes = 1000 * 60 * 10;
long oneHourFromNow = (new Date()).getTime() + oneHour;
long tenMinutesFromNow = (new Date()).getTime() + tenMinutes;
String calendarString = calendarIdSpinner.getSelectedItem().toString();
int calendar_id = Integer.parseInt(calendarIdTable.get(calendarString));
CalendarHelper.MakeNewCalendarEntry(this, "Test", "Add event", "Somewhere",tenMinutesFromNow,tenMinutesFromNow+oneHour,false,true,calendar_id,3);
}
}
Create class for calendar selection
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
private static final String TAG = "OnItemSelectedListener";
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.v(TAG,"onNohingSelected() called.");
}
}
CalendarHelper.java
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.TimeZone;
public class CalendarHelper {
//Remember to initialize this activityObj first, by calling initActivityObj(this) from
//your activity
private static final String TAG = "CalendarHelper";
public static final int CALENDARHELPER_PERMISSION_REQUEST_CODE = 99;
public static void MakeNewCalendarEntry(Activity caller,String title,String description,String location,long startTime,long endTime, boolean allDay,boolean hasAlarm, int calendarId,int selectedReminderValue) {
ContentResolver cr = caller.getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startTime);
values.put(Events.DTEND, endTime);
values.put(Events.TITLE, title);
values.put(Events.DESCRIPTION, description);
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.STATUS, Events.STATUS_CONFIRMED);
if (allDay)
{
values.put(Events.ALL_DAY, true);
}
if (hasAlarm)
{
values.put(Events.HAS_ALARM, true);
}
//Get current timezone
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Log.i(TAG, "Timezone retrieved=>"+TimeZone.getDefault().getID());
Uri uri = cr.insert(Events.CONTENT_URI, values);
Log.i(TAG, "Uri returned=>"+uri.toString());
// get the event ID that is the last element in the Uri
long eventID = Long.parseLong(uri.getLastPathSegment());
if (hasAlarm)
{
ContentValues reminders = new ContentValues();
reminders.put(Reminders.EVENT_ID, eventID);
reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
reminders.put(Reminders.MINUTES, selectedReminderValue);
Uri uri2 = cr.insert(Reminders.CONTENT_URI, reminders);
}
}
public static void requestCalendarReadWritePermission(Activity caller)
{
List<String> permissionList = new ArrayList<String>();
if (ContextCompat.checkSelfPermission(caller,Manifest.permission.WRITE_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
{
permissionList.add(Manifest.permission.WRITE_CALENDAR);
}
if (ContextCompat.checkSelfPermission(caller,Manifest.permission.READ_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
{
permissionList.add(Manifest.permission.READ_CALENDAR);
}
if (permissionList.size()>0)
{
String [] permissionArray = new String[permissionList.size()];
for (int i=0;i<permissionList.size();i++)
{
permissionArray[i] = permissionList.get(i);
}
ActivityCompat.requestPermissions(caller,
permissionArray,
CALENDARHELPER_PERMISSION_REQUEST_CODE);
}
}
public static Hashtable listCalendarId(Context c) {
if (haveCalendarReadWritePermissions((Activity)c)) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst())
{
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String,String> calendarIdTable = new Hashtable<>();
do
{
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName,calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
return null;
}
public static boolean haveCalendarReadWritePermissions(Activity caller)
{
int permissionCheck = ContextCompat.checkSelfPermission(caller,
Manifest.permission.READ_CALENDAR);
if (permissionCheck== PackageManager.PERMISSION_GRANTED)
{
permissionCheck = ContextCompat.checkSelfPermission(caller,
Manifest.permission.WRITE_CALENDAR);
if (permissionCheck== PackageManager.PERMISSION_GRANTED)
{
return true;
}
}
return false;
}
}

Related

How to generate CSV file from Android Studio Table Layout

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;
}}

How to get Audio path from listview

I am creating mp3 player unable to get audio path URI using media.uri.data is not working please help me how get path audio file path?
Here is my code. I am searching lot but did not found the answer media.uri.data is return null what should do?I am unable stuck only in this step help?
package com.monstertechno.musicplayerappui;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.renderscript.Sampler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
private ArrayList<Song> songList;
private ListView songView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runtimpermission();
songView = (ListView) findViewById(R.id.song_list);
songList = new ArrayList<Song>();
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
getSongList();
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mediaPlayer!=null){
mediaPlayer.release();
}
}
});
}
public void runtimpermission(){
Dexter.withActivity(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override public void onPermissionGranted(PermissionGrantedResponse response) {
Toast.makeText(MainActivity.this, "Permisson Access", Toast.LENGTH_SHORT).show();
}
#Override public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(MainActivity.this, "Permisson Denied", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();}
}).check();
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
}
Okay you were'nt clear enough,I add a complete code in case any body needs it you only need one line of it though:
Cursor cur = cr.query(uri, null, selection, null, sortOrder);
int count = 0;
if (cur != null) {
count = cur.getCount();
if (count > 0) {
while (cur.moveToNext()) {
String album = (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
String artist = (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
String title =(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)));
String path = (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)));
String alumbId =(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
long duration = (cur.getLong(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)));
Cursor cursorImage = getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART}, MediaStore.Audio.Albums._ID+ "=?", new String[] {String.valueOf(alumbId)}, null);
assert cursorImage != null;
if (cursorImage.moveToFirst()) {
String imagePath = cursorImage.getString(cursorImage.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
}
}
}
}
cur.close();
It works I just tested it.Just check for null for imagePath.

The input does not show on the ListView

I followed this instruction http://www.vogella.com/tutorials/AndroidSQLite/article.html
Normally after I input a string(tag), it should be shown on the Listview, but instead I keep seeing the string that shows when there are no data in the database I created.
MainActivity.java
package ch.ethz.twimight.activities;
import android.app.ListActivity;
import android.os.Bundle;
import ch.ethz.twimight.R;
import ch.ethz.twimight.net.twitter.Tags;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MytagsActivity extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int ACTIVITY_CREATE = 0;
private static final int DELETE_ID = Menu.FIRST + 1;
private SimpleCursorAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mytags);
this.getListView().setDividerHeight(2);
fillData();
registerForContextMenu(getListView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_tags, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Add:
createTodo();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Uri uri = Uri.parse(Tags.CONTENT_URI + "/"
+ info.id);
getContentResolver().delete(uri, null, null);
//fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createTodo() {
Intent i = new Intent(this, MyTagsActivity_D.class);
startActivity(i);
}
private void fillData() {
// Fields from the database (projection)
// Must include the _id column for the adapter to work
String[] from = new String[] { Tags.COL_TEXT };
// Fields on the UI to which we map
int[] to = new int[] { R.id.label };
//getLoaderManager().initLoader(0, null, this);
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.mytags_row, null, from,
to, 0);
setListAdapter(adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.delete_tag);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
String[] projection = { Tags.COL_ROW_ID, Tags.COL_TEXT};
CursorLoader cursorLoader = new CursorLoader(this,
Tags.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
// TODO Auto-generated method stub
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// TODO Auto-generated method stub
adapter.swapCursor(null);
}
}
layout.xml
<?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="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/no_tags" />
</LinearLayout>
layout_row.xml:
<?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="wrap_content" >
<ImageView
android:id="#+id/icon"
android:layout_width="30dp"
android:layout_height="24dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:src="#drawable/ic_tag" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:lines="1"
android:text="#+id/TextView01"
android:textSize="24sp" >
</TextView>
</LinearLayout>
layout_edit.xml
<?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="vertical" >
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/addtag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/new_tag"
android:imeOptions="actionNext" >
</EditText>
</LinearLayout>
<Button
android:id="#+id/ilikeit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ilikeit" >
</Button>
</LinearLayout>
ContentProvider.java:
package ch.ethz.twimight.net.twitter;
import java.util.Arrays;
import java.util.HashSet;
import ch.ethz.twimight.data.DBOpenHelper;
import android.content.ContentProvider;
import android.content.ContentValues;
//import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
public class TagsContentProvider extends ContentProvider{
private static final String TAG = TagsContentProvider.class.getSimpleName();
private SQLiteDatabase database;
private DBOpenHelper dbHelper;
private static final UriMatcher tagsUriMatcher;
private static final int TAGS = 1;
private static final int TAGS_ID = 2;
static {
tagsUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
tagsUriMatcher.addURI(Tags.TAG_AUTHORITY, Tags.TAGS, TAGS);
tagsUriMatcher.addURI(Tags.TAG_AUTHORITY, Tags.TAGS + "/#", TAGS_ID);
#Override
public synchronized int delete(Uri uri, String arg1, String[] arg2) {
if (tagsUriMatcher.match(uri) != TAGS_ID)
throw new IllegalArgumentException("Unsupported URI: " + uri);
Log.d(TAG, "Delete TAGS_ID");
int nrRows = database.delete(DBOpenHelper.TABLE_TAGS, "_id=" + uri.getLastPathSegment(), null);
getContext().getContentResolver().notifyChange(Tags.CONTENT_URI, null);
return nrRows;
}
#Override
public String getType(Uri uri) {
switch (tagsUriMatcher.match(uri)) {
case TAGS:
return Tags.TAGS_CONTENT_TYPE;
case TAGS_ID:
return Tags.TAG_CONTENT_TYPE;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
private void checkColumns(String[] projection) {
String[] available = {DBOpenHelper.COL_ROW_ID };
if (projection != null) {
HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
// check if all columns which are requested are available
if (!availableColumns.containsAll(requestedColumns)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}
}
#Override
public synchronized Uri insert(Uri uri, ContentValues values) {
//int uriType = tagsUriMatcher.match(uri);
// SQLiteDatabase sqlDB = database.getWritableDatabase();
//int rowsDeleted = 0;
long id = 0;
switch (tagsUriMatcher.match(uri)) {
case TAGS:
id = database.insert(DBOpenHelper.TABLE_TAGS, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(Tags.TAGS + "/" + id);
}
#Override
public boolean onCreate() {
dbHelper = DBOpenHelper.getInstance(getContext().getApplicationContext());
database = dbHelper.getWritableDatabase();
return true;
}
#Override
public synchronized Cursor query(Uri uri, String[] projection, String where, String[] whereArgs, String sortOrder) {
if (TextUtils.isEmpty(sortOrder))
sortOrder = Tags.DEFAULT_SORT_ORDER;
checkColumns(projection);
Cursor c = null;
String sql = null;
//Intent i = null;
switch (tagsUriMatcher.match(uri)) {
case TAGS:
Log.d(TAG, "Query TAGS");
c = database.query(DBOpenHelper.TABLE_TAGS, projection, where, whereArgs, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), Tags.CONTENT_URI);
break;
case TAGS_ID:
Log.d(TAG, "Query TAGS_ID");
sql = "SELECT * " + "FROM " + DBOpenHelper.TABLE_TAGS + " " + "WHERE " + DBOpenHelper.TABLE_TAGS + "._id="
+ uri.getLastPathSegment() + ";";
c = database.rawQuery(sql, null);
c.setNotificationUri(getContext().getContentResolver(), uri);
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
return c;
}
#Override
public synchronized int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int nrRows = database.update(DBOpenHelper.TABLE_TAGS, values, "_id=" + uri.getLastPathSegment(), null);
switch (tagsUriMatcher.match(uri)){
case TAGS:
nrRows = database.update(DBOpenHelper.TABLE_TAGS,
values,
selection,
selectionArgs);
break;
case TAGS_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
nrRows = database.update(DBOpenHelper.TABLE_TAGS,
values,
DBOpenHelper.COL_ROW_ID + "=" + id,
null);
} else {
nrRows = database.update(DBOpenHelper.TABLE_TAGS,
values,
DBOpenHelper.COL_ROW_ID + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return nrRows;
}
}
And here is the logcat I got after I input a string:
W/ResourceType(10480): Skipping entry 0x1060072 in package table 0 because it is not complex!
D/TextView(10480): Constructor - Got appearance for textColorPrimaryInverse
D/TextView(10480): Constructor -- Got mEditTextBackgroundColor
W/IInputConnectionWrapper(10480): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(10480): endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(10480): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(10480): endBatchEdit on inactive InputConnection
I must have missed something...I am stucked here for two days...
I checked other example codes but still couldn't figure out what I've missed.
Please help, thank you.

showing the content of the table in database a list cannot be undone

I have just started to learn programming and I try to build a simple database for my exercise and I try to show all the content of the table in my database into a list in another layout but I don't know why the content isn't showing up in the list.. please help me ..
here is my apps sample
here is my activity for putting all the content in the list:
package com.DennisTA;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class DaftarIstilah extends Activity{
private DataKamus dbhelper;
private SQLiteDatabase db = null;
private ListView listContent = null;
private Cursor kamusCursor = null;
CustomCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbhelper = new DataKamus(this);
setContentView(R.layout.daftaristilah);
listContent = (ListView) findViewById(R.id.list1);
isDataListView();
}
private void isDataListView() {
try {
db = dbhelper.getWritableDatabase();
kamusCursor = db.query("kamus", new String[] { "_id", "inggris",
"arti", "penjelasan" }, "_id>0", null, null, null, null);
// startManagingCursor( jasaCursor);
/*
* Create an array to specify the fields we want to display in the
* list (only the 'inggris,arti,penjelasan' column in this case)
*/
String[] from = new String[] { "inggris", "arti", "penjelasan" };
/*
* and an array of the fields we want to bind those fieiplds to (in
* this case just the textView 'inggris,arti,penjelasan' from our new row.xml
* layout above)
*/
int[] to = new int[] { R.id.inggris, R.id.arti, R.id.penjelasan };
/* Now create a simple cursor adapter.. */
adapter = new CustomCursorAdapter(this, R.layout.baris, kamusCursor,
from, to);
// listView.setAdapter(adapter);
listContent.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
} catch (Exception e) {
}
}
protected class CustomCursorAdapter extends SimpleCursorAdapter {
private int layout;
private LayoutInflater inflater;
private Context context;
public CustomCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super (context, layout, c, from, to);
this.layout = layout;
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Log.d("NewView", "*****xxx");
View v = inflater.inflate(R.layout.baris, parent, false);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
// 1 is the column where you're getting your data from
String inggris = c.getString(1);
String penjelasan = c.getString(3);
String arti = c.getString(2);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.inggris);
TextView des_text = (TextView) v.findViewById(R.id.penjelasan);
TextView id_text = (TextView) v.findViewById(R.id.arti);
des_text.setText(penjelasan);
id_text.setText(arti);
if (name_text != null) {
name_text.setText(inggris);
}
}
}
}
here is my baris.xml sample :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:paddingBottom="5sp"
android:paddingTop="5sp" >
<TextView
android:id="#+id/inggris"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/arti"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/inggris" />
<TextView
android:id="#+id/penjelasan"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/arti" />
</RelativeLayout>
here is my daftar istilah.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text = "Inggris"
android:textSize="20sp" />
<TextView
android:id="#+id/textView2"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:text = "Arti"
android:textSize="20sp" />
<TextView
android:id="#+id/textView3"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView2"
android:text = "Penjelasan"
android:textSize="20sp" />
<ListView android:id="#+id/list1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight = "1"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"/>
</RelativeLayout>
here is my class that contain the database:
package com.DennisTA;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataKamus extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbkamus";
public static final String INGGRIS= "inggris";
public static final String ARTI = "arti";
public static final String PENJELASAN = "penjelasan";
//Constructor DataKamus untuk initiate database
public DataKamus(Context context) {
super(context, DATABASE_NAME, null, 1);
}
//method createTable untuk membuat table kamus
public void createTable(SQLiteDatabase db){
db.execSQL("DROP TABLE IF EXISTS kamus");
db.execSQL("CREATE TABLE if not exists kamus (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"inggris TEXT, arti TEXT, penjelasan TEXT);");
}
//method generateData untuk mengisikan data ke kamus.
public void generateData(SQLiteDatabase db){
ContentValues cv=new ContentValues();
cv.put(INGGRIS, "run");
cv.put(ARTI, "lari");
cv.put(PENJELASAN, "laufen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "walk");
cv.put(ARTI, "jalan");
cv.put(PENJELASAN, "gehen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "read");
cv.put(ARTI, "membaca");
cv.put(PENJELASAN, "lesen");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
createTable(db);
generateData(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), "Oncreate", Toast.LENGTH_SHORT).show();
createTable(db);
generateData(db);
}
}
here is my main activity :
package com.DennisTA;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db = null;
private Cursor kamusCursor = null;
private EditText txtInggris;
private EditText txtArti;
private EditText txtPenjelasan;
private DataKamus datakamus = null;
public static final String INGGRIS = "inggris";
public static final String ARTI = "arti";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datakamus = new DataKamus(this);
db = datakamus.getWritableDatabase();
setContentView(R.layout.activity_main);
txtInggris = (EditText) findViewById(R.id.txtInggris);
txtArti = (EditText) findViewById(R.id.txtArti);
txtPenjelasan = (EditText) findViewById(R.id.txtPenjelasan);
}
public void getTerjemahan(View view) {
String bhsindonesia = "";
String bhsjerman="";
String englishword = txtInggris.getText().toString();
kamusCursor = db.rawQuery("SELECT _ID, INGGRIS, INDONESIA, JERMAN " + "FROM kamus where INGGRIS='" + englishword + "' ORDER BY INGGRIS", null);
if (kamusCursor.moveToFirst()) {
for (; !kamusCursor.isAfterLast();
kamusCursor.moveToNext()) {
bhsindonesia = kamusCursor.getString(2);
bhsjerman = kamusCursor.getString(3);
}
}else{
Toast.makeText(getBaseContext(), "Terjemahan Tidak ditemukan", Toast.LENGTH_SHORT).show();
}
txtArti.setText(bhsindonesia);
txtPenjelasan.setText(bhsjerman);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
db.close();
}catch (Exception e){
}
}
}
Retrieving from database as follows:
String selectQuery = "SELECT * FROM " + Variables.TABLE_ORDER
+ " WHERE " + Variables.TABLE_ORDER_CATEGORY ;
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Food_Id", cursor.getString(0));
cart_Array_List.add(map);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
}
Try extending a BaseAdapter and ovverride the following method:
#Override
public int getCount() {
return arraylist.size();
}

Customize text inside Edittext for chatting

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.

Categories

Resources