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;
}}
Related
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;
}
}
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.
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();
}
I would like to create a programm that reads a plain text file then either lists all the items in the text file or lists items depending on what the user types in and which button is pressed. I haven't been able to run it yet, as there are a number of errors. I have attempted to use the developer.android.com website, youTube and google to find solutions but the more I adjust the code the worse the problems seem to get. Below are the pieces of code I have come up with so far, including the text file, the manifest and fragment files.
info_sample.txt
Equipment Type Equipment ID Location Status Time
Infusion Pump 1234 2 On 12:00
Hoist 3645 1 Off 13:00
Bed 2563 3 Occupied 14:00
fragment_cemmain.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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="clinical.equipment.monitor.CEMMainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/equiptype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/equiptype" />
<EditText
android:id="#+id/equiptypetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/equiptype"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/equipid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/equiptypetext"
android:layout_marginTop="28dp"
android:text="#string/equipid" />
<EditText
android:id="#+id/equipidtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/equipid"
android:ems="10" />
<Button
android:id="#+id/findequip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/equipidtext"
android:text="#string/findequip"
android:onClick="findequip" />
<Button
android:id="#+id/listallequip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/findequip"
android:layout_alignBottom="#+id/findequip"
android:layout_toRightOf="#+id/findequip"
android:text="#string/listallequip"
android:onClick="listallequip" />
<Button
android:id="#+id/refreshall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/linearLayout1"
android:layout_alignParentLeft="true"
android:layout_marginBottom="27dp"
android:onClick="refreshall"
android:text="#string/refresh" />
<Button
android:id="#+id/cleartext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/findequip"
android:layout_marginTop="56dp"
android:onClick="cleartext"
android:text="#string/cleartext" />
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
CEMMainActivity.java
package clinical.equipment.monitor;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.os.Build;
import android.provider.ContactsContract;
public class CEMMainActivity extends ActionBarActivity {
public class ListViewLoader extends ListActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
// This is the Adapter being used to display the list's data
SimpleCursorAdapter mAdapter;
// These are the Contacts rows that we will retrieve
static final String[] PROJECTION = new String[] {ContactsContract.Data._ID,
ContactsContract.Data.DISPLAY_NAME};
// This is the select criteria
static final String SELECTION = "((" +
ContactsContract.Data.DISPLAY_NAME + " NOTNULL) AND (" +
ContactsContract.Data.DISPLAY_NAME + " != '' ))";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cemmain);
if (savedInstanceState == null) {// action if app does not start up correctly
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
// Clears all text in EditText fields
Button clearalltext = (Button) findViewById(R.id.cleartext);
clearalltext.setOnClickListener(new OnClickListener() {
public void onClick(View c) {
ViewGroup group = (ViewGroup) findViewById(R.id.cleartext);
clearText(group);
for (int i = 0, count = group.getChildCount(); i < count; ++i) {
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
clearText((ViewGroup)group);
}
}
});
//Action once Find button is clicked
Button findequip = (Button)findViewById(R.id.findequip);
findequip.setOnClickListener(new OnClickListener() {
public void onClick(View f) {
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Cursor c = db.getWordMatches(query, null);
//process Cursor and display results
}
}
}
}
});
// ignores the text fields and lists all equipment in virtual table
Button listalldatabase = (Button)findViewById(R.id.listallequip);
listalldatabase.setOnClickListener(new OnClickListener(){// may need correction
public void onClick(View l) {
//meant to call DatabaseOpenHelper class
}
} );
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cemmain, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_cemmain,
container, false);
return rootView;
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="clinical.equipment.monitor"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="clinical.equipment.monitor.CEMMainActivity"
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>
DatabaseOpenHelper.java
package clinical.equipment.monitor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class DatabaseOpenHelper {
private static final String TAG = "ListAllEquipment";
//The columns to be included in table
public static final String COL_TYPE = "EQUIPMENT TYPE";
public static final String COL_ID = "ID";
public static final String COL_LOCATION = "LOCATION";
public static final String COL_STATUS = "STATUS";
public static final String COL_TIME = "TIME";
private static final String DATABASE_NAME = "EQUIPMENT LIST";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
public DatabaseOpenHelper(Context context) {
// TODO Auto-generated constructor stub
}
public void Listalldatabase (Context context) {
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
private static class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +
COL_TYPE + ", " +
COL_ID + ", " + COL_LOCATION + ", " + COL_STATUS +", " + COL_TIME + ")";
DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelperContext = context;
}
// populate the virtual table
private void loadEquipmentList() {
new Thread(new Runnable() {
public void run() {
try {
loadType();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadType() throws IOException {
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.info_sample);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 5) continue;
long list = addItem(strings[0].trim(), strings[1].trim(), strings[2].trim(), strings[3].trim(), strings[4].trim());
if (list < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
public long addItem (String type; String id; String location; String status; String time); {
ContentValues initialValues = new ContentValues();
initialValues.put(COL_TYPE, type);
initialValues.put(COL_ID, id);
initialValues.put(COL_LOCATION, location);
initialValues.put(COL_STATUS, status);
initialValues.put(COL_TIME, time);
return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
}
#Override
public void onCreate(SQLiteDatabase list) {
SQLiteDatabase mDatabase = list;
mDatabase.execSQL(FTS_TABLE_CREATE);
loadEquipmentList();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
}
}
SearchForEquip.java
package clinical.equipment.monitor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.text.*;
import android.util.Log;
public class SearchForEquip {
String equiptypetext,equipidtext, input1, input2;
private boolean readytofind() {
String input1 = equiptypetext.toString();
String input2 = equipidtext.toString();
if ((input1 != null) && (input2 != null))
{ return ((input1 != null) &&( input2 != null));
}
else if ((input1 == null) && (input2 != null))
{ return (input2 != null);
}
else if ((input1 != null) && (input2 == null)) {
return (input1 != null);
}
else { return false;}
}
public class DatabaseOpen {
private static final String TAG = "FindEquipment";
//The columns to be included in table
public static final String COL_TYPE = "EQUIPMENT TYPE";
public static final String COL_ID = "ID";
public static final String COL_LOCATION = "LOCATION";
public static final String COL_STATUS = "STATUS";
public static final String COL_TIME = "TIME";
private static final String DATABASE_NAME = "EQUIPMENT FOUND";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final static DatabaseOpen mDatabaseOpen;
public DatabaseOpen(Context item) {
// TODO Auto-generated constructor stub
}
public void DatabaseTable(Context item) {
mDatabaseOpen = new DatabaseOpen(item);
}
private static class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mContext;
private SQLiteDatabase mSearch;
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +
COL_TYPE + ", " +
COL_ID + ", " + COL_LOCATION + ", " + COL_STATUS +", " + COL_TIME + ")";
private static final Context mHelper = null;
DatabaseOpen(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelper = item;
}
//here the code should compare the typed text to the text in the text file and return a match
public Cursor getMatches(String query, String[] columns) {
String selection1 = COL_TYPE + " MATCH ?";
String selection2 = COL_ID + "MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection1, selection2, selectionArgs, columns);
}
private Cursor query(String selection, String[] selectionArgs, String[] columns) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS_VIRTUAL_TABLE);
Cursor cursor = builder.query(mDatabaseOpen.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
// populate the virtual table
private void loadSearchList() {
new Thread(new Runnable() {
public void run() {
try {
loadType();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadEquip() throws IOException {
final Resources equip = mHelper.getResources();
InputStream inputStream = equip.openRawResource(R.raw.info_sample);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 5) continue;
long list = addItem(strings[0].trim(), strings[1].trim(), strings[2].trim(), strings[3].trim(), strings[4].trim());
if (list < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally { reader.close();}
public long addItem (String type, String id, String location, String status, String time) {
ContentValues initialValues = new ContentValues();
initialValues.put(COL_TYPE, type);
initialValues.put(COL_ID, id);
initialValues.put(COL_LOCATION, location);
initialValues.put(COL_STATUS, status);
initialValues.put(COL_TIME, time);
return mSearch.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
}
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...