problem using facebook SDK - Android Q&A, Help & Troubleshooting

Hi i have problem capturing the information using the facebook SDK.
The console dont show any error but capture nothing.
In this code below i want to capture the name provided by the facebook SDK
Code:
package com.eduardoh89saluguia;
import java.util.List;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
@SuppressWarnings("unused")
public class Registro extends Activity {
String get_id, get_name, get_gender, get_email, get_birthday, get_locale, get_location;
private Session.StatusCallback fbStatusCallback = new Session.StatusCallback() {
public void call(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
if (response != null) {
String LOG_TAG = null;
// do something with <response> now
try{
// get_id = user.getId();
get_name = user.getName();
//get_gender = (String) user.getProperty("gender");
//get_email = (String) user.getProperty("email");
//get_birthday = user.getBirthday();
//get_locale = (String) user.getProperty("locale");
//get_location = user.getLocation().toString();
Log.d(LOG_TAG, user.getId() + "; " +
user.getName() + "; " //+
//(String) user.getProperty("gender") + "; " +
//(String) user.getProperty("email") + "; " +
//user.getBirthday()+ "; " +
//String) user.getProperty("locale") + "; " +
//user.getLocation()
);
TextView temp;
temp =(TextView)findViewById(R.id.edit1);
temp.setText("your name is "+get_name);
} catch(Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Exception e");
}
}
}
}).executeAsync();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(), Ejecucion.class);
startActivity(i);
}
});
}
private Session openActiveSession(Activity activity, boolean allowLoginUI,
StatusCallback callback, List<String> permissions, Bundle savedInstanceState) {
OpenRequest openRequest = new OpenRequest(activity).
setPermissions(permissions).setLoginBehavior(SessionLoginBehavior.
SSO_WITH_FALLBACK).setCallback(callback).
setDefaultAudience(SessionDefaultAudience.FRIENDS);
String LOG_TAG = null;
Session session = Session.getActiveSession();
Log.d(LOG_TAG, "" + session);
if (session == null) {
Log.d(LOG_TAG, "" + savedInstanceState);
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, fbStatusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED) || allowLoginUI) {
session.openForRead(openRequest);
return session;
}
}
return null;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.registro, 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);
}
}

Related

[Q] How to monitor socket status on simple tcp client

I have currently created a simple tcp socket client application that sends and receives messages from a dotnet server application I have created. The application itself actually works however there are a few things I would like to know if they are possible or not. Also this is my first ever droid application and my first ever java application so I am sure there is a better way to do what I have written so please go easy on me.
The problem that I am having is I need a way to monitor the status of the socket so that if the connection gets dropped whether it is from the server application ending or a network drop that the android client would disconnect and put a notification on the screen letting me know. Currently if I end the server application nothign happens on the client and it acts like the connection is still open. Granted this is probably due to the way I have it written so I am looking for samples or suggestions on how to change this so I can monitor this. Any help would be great. Eventually this will be put into a much larger project for my home but I am starting off small so I can do it correctly the first time rather than having someing messy later on.
My code is listed below.
Thanks
KJ
Source:
package com.kkearney.tcp1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TCPClient1Activity extends Activity {
public static final int BUFFER_SIZE = 2048;
private Socket sck = null;
private PrintWriter out = null;
private BufferedReader in = null;
Button btnSend;
Button btnConnect;
Button btnDisconnect;
EditText textOut;
TextView textIn;
String response = "";
final Handler handler = new Handler();
final Runnable updateUI = new Runnable() {
public void run() {
textIn.setText(response);
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.txtSend);
textIn = (TextView)findViewById(R.id.txtMSG);
btnSend = (Button)findViewById(R.id.btnSend);
btnConnect = (Button)findViewById(R.id.btnConnect);
btnDisconnect = (Button)findViewById(R.id.btnDisconnect);
}
public void ConnectUp(View view){
OpenConnection();
}
public void OpenConnection(){
new Thread(new Runnable(){
public void run(){
try{
if (sck == null){
sck = new Socket("10.0.0.135",8080);
sck.setKeepAlive(true);
screenConfig();
in = new BufferedReader(new InputStreamReader(sck.getInputStream()));
out = new PrintWriter(sck.getOutputStream());
sendDataWithString("testing 1 2 3");
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = in.read(buffer)) != -1) {
response += new String(buffer).substring(0, charsRead);
handler.post( updateUI );
}
screenConfig();
}
}
catch (IOException e) {
System.out.print(e+"");
}
catch (Exception e) {
System.out.print(e+"");
}
}
}).start();
}
public void screenConfig(){
if (sck.isClosed() == false){
textOut.setClickable(true);
btnSend.setClickable(true);
btnDisconnect.setClickable(true);
btnConnect.setClickable(false);
}else{
textOut.setClickable(false);
btnSend.setClickable(false);
btnDisconnect.setClickable(false);
btnConnect.setClickable(true);
}
}
public void SendMessage(View view){
sendDataWithString(textOut.getText().toString());
textOut.setText(null);
}
public void DisConnect(View view){
CloseConnection();
}
public void CloseConnection(){
if (sck != null) {
try {
sck.close();
screenConfig();
} catch (IOException e) {
e.printStackTrace();
} finally {
sck = null;
}
}
}
public void sendDataWithString(String message) {
if (message != null && sck != null) {
out.write(message);
out.flush();
}
}
}

android quiz help

So I've decided to to teach myself how to program for android and have a general understanding for java. Well i decided to borrow someones code from the internet and utilize it to assist in creating my first quiz app. I am getting some errors in this code and was wondering if anyone would be so kind to assist me. Thanks
Code:
package com.danyluk.MedicStudyGuide;
import java.io.IOException;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class Quiz extends Activity{
/** Called when the activity is first created. */
private RadioButton radioButton;
private TextView quizQuestion;
private TextView tvScore;
private int rowIndex = 1;
private static int score=0;
private int questNo=0;
private boolean checked=false;
private boolean flag=true;
private RadioGroup radioGroup;
String[] corrAns = new String[5];
final DataBaseHelper db = new DataBaseHelper(this);
Cursor c1;
Cursor c2;
Cursor c3;
int counter=1;
String label;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz);
String options[] = new String[19];
// get reference to radio group in layout
RadioGroup radiogroup = (RadioGroup) findViewById(R.id.rdbGp1);
// layout params to use when adding each radio button
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
try {
db.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c3 = db.getCorrAns();
tvScore = (TextView) findViewById(R.id.tvScore);
for (int i=0;i<=4;i++)
{
corrAns[i]=c3.getString(0);
c3.moveToNext();
}
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
for(int i=0;;){
RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
String text;
if (btn.isPressed() && btn.isChecked() && questNo < 5)
{
Log.e("corrAns[questNo]",corrAns[questNo]);
if (corrAns[questNo].equals(btn.getText()) && flag==true)
{
score++;
flag=false;
checked = true;
}
else if(checked==true)
{
score--;
flag=true;
checked = false;
}
}
}
tvScore.setText = ("Score: " + Integer.toString(score) + "/5");
Log.e("Score:", Integer.toString(score));
}
});
quizQuestion = (TextView) findViewById(R.id.TextView01);
displayQuestion();
/*Displays the next options and sets listener on next button*/
Button btnNext = (Button) findViewById(R.id.btnNext);
btnNext.setOnClickListener(btnNext_Listener);
/*Saves the selected values in the database on the save button*/
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(btnSave_Listener);
}
/*Called when next button is clicked*/
private View.OnClickListener btnNext_Listener= new View.OnClickListener() {
@Override
public void onClick(View v) {
flag=true;
checked = false;
questNo++;
if (questNo < 5)
{
c1.moveToNext();
displayQuestion();
}
}
};
/*Called when save button is clicked*/
private View.OnClickListener btnSave_Listener= new View.OnClickListener() {
@Override
public void onClick(View v) {
}
};
private void displayQuestion()
{
//Fetching data quiz data and incrementing on each click
c1=db.getQuiz_Content(rowIndex);
c2 =db.getAns(rowIndex++);
quizQuestion.setText(c1.getString(0));
radioGroup.removeAllViews();
for (int i=0;i<=3;i++)
{
//Generating and adding 4 radio buttons dynamically
radioButton = new RadioButton(this);
radioButton.setText(c2.getString(0));
radioButton.setId(i);
c2.moveToNext();
radioGroup.addView(radioButton);
}
}}}
You forgot give us the error that you get

Android SQLLite Sample

Android SQLLite Sample
hello guys im new for xda, and this is a my first thread.please give me your feed back.
DataBase Setting Java File
Code:
package com.example.mydsqllite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBCon extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "myDoople";
private static final String TABLE_LABELS = "Customer";
private static final String KEY_ID = "ID";
private static final String KEY_NAME = "CName";
public DBCon(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
db.insert(TABLE_LABELS, null, values);
db.close();
}
/**
* Getting all labels returns list of labels
* */
public void deleteLabel(String label1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label1);
db.delete(TABLE_LABELS, KEY_NAME + "=?", new String[] {label1});
db.close();
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return labels;
}
}
Main Activity File
Code:
package com.example.mydsqllite;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener,
OnItemSelectedListener {
private Spinner sp;
private Button bt;
private Button dl;
private EditText tx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UI();
InitSpinner();
}
public void UI() {
sp = (Spinner) findViewById(R.id.spinner1);
sp.setOnItemSelectedListener(this);
bt = (Button) findViewById(R.id.btUpdate);
bt.setOnClickListener(this);
dl = (Button) findViewById(R.id.btDel);
dl.setOnClickListener(this);
tx = (EditText) findViewById(R.id.TxtCus);
}
private void InitSpinner() {
DBCon db = new DBCon(getApplicationContext());
List<String> lables = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(dataAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String label = arg0.getItemAtPosition(arg2).toString();
Toast.makeText(arg0.getContext(), "Customer Name : " + label,
Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
@Override
public void onClick(View v) {
if (v == bt) {
String label = tx.getText().toString();
if (label.trim().length() > 0) {
DBCon db = new DBCon(getApplicationContext());
db.insertLabel(label);
tx.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tx.getWindowToken(), 0);
InitSpinner();
}
} else if (v == dl) {
String CName = tx.getText().toString();
if (CName.trim().length() > 0) {
DBCon db = new DBCon(getApplicationContext());
db.deleteLabel(CName);
tx.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tx.getWindowToken(), 0);
InitSpinner();
}
} else {
Toast.makeText(getApplicationContext(), "Please Enter Customer Name",
Toast.LENGTH_SHORT).show();
}
}
}
mydoople said:
Android SQLLite Sample
hello guys im new for xda, and this is a my first thread.please give me your feed back.
DataBase Setting Java File
Code:
package com.example.mydsqllite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBCon extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "myDoople";
private static final String TABLE_LABELS = "Customer";
private static final String KEY_ID = "ID";
private static final String KEY_NAME = "CName";
public DBCon(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
db.insert(TABLE_LABELS, null, values);
db.close();
}
/**
* Getting all labels returns list of labels
* */
public void deleteLabel(String label1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label1);
db.delete(TABLE_LABELS, KEY_NAME + "=?", new String[] {label1});
db.close();
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return labels;
}
}
Main Activity File
Code:
package com.example.mydsqllite;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener,
OnItemSelectedListener {
private Spinner sp;
private Button bt;
private Button dl;
private EditText tx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UI();
InitSpinner();
}
public void UI() {
sp = (Spinner) findViewById(R.id.spinner1);
sp.setOnItemSelectedListener(this);
bt = (Button) findViewById(R.id.btUpdate);
bt.setOnClickListener(this);
dl = (Button) findViewById(R.id.btDel);
dl.setOnClickListener(this);
tx = (EditText) findViewById(R.id.TxtCus);
}
private void InitSpinner() {
DBCon db = new DBCon(getApplicationContext());
List<String> lables = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(dataAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String label = arg0.getItemAtPosition(arg2).toString();
Toast.makeText(arg0.getContext(), "Customer Name : " + label,
Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
@Override
public void onClick(View v) {
if (v == bt) {
String label = tx.getText().toString();
if (label.trim().length() > 0) {
DBCon db = new DBCon(getApplicationContext());
db.insertLabel(label);
tx.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tx.getWindowToken(), 0);
InitSpinner();
}
} else if (v == dl) {
String CName = tx.getText().toString();
if (CName.trim().length() > 0) {
DBCon db = new DBCon(getApplicationContext());
db.deleteLabel(CName);
tx.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tx.getWindowToken(), 0);
InitSpinner();
}
} else {
Toast.makeText(getApplicationContext(), "Please Enter Customer Name",
Toast.LENGTH_SHORT).show();
}
}
}
Click to expand...
Click to collapse
So what is exactly the point of this thread?

Unsure of issue New developer : Null pointer Exception

Hello Iv been developing my app for around 2 weeks now and Iv hit a bug were I'm getting a null pointer Exception error iv been going around and around in circles trying to figure out what I'm doing wrong but im completely new to programming iv posted my code below and if you have any idea what im doing wrong please tell me
mainActivity
package com.example.joelg.clapp;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ListView lstJob;
IntDataBaseHelper myhelper = new IntDataBaseHelper(this);
ArrayAdapter<String> mAdapter;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*create instance of db helper and jobs
Create the database (only if it doesn't exists)
does so by copying from the assets */
LoadJobList();
if (CopyDBFromAssets.createDataBase(this,IntDataBaseHelper.DB_TABLE)) {
// problem area
// Get the data from the database
lstJob = (ListView) findViewById(R.id.lstJob);
ArrayList<String> jobs = myhelper.getJobList();
for (String s : jobs) {
Log.d("JobList ", "Found Job " + s);
}
} else {
throw new RuntimeException("No Usable Database exists or was copied from the assets.");
}
}
// loads job to screen
public void LoadJobList() {
ArrayList<String> JobList = myhelper.getJobList();
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,R.layout.header,R.id.header);
mAdapter = new ArrayAdapter<>(this,R.layout.row,R.id.BtnComplete,JobList);
mAdapter = new ArrayAdapter<>(this, R.layout.row, R.id.Job_name,JobList);
lstJob.setAdapter(mAdapter);
} else
{
mAdapter.clear();
mAdapter.addAll(JobList);
mAdapter.notifyDataSetChanged();
}
}
}
// public void JobComplete(View view){
// View parent = (View)view.getParent();
// TextView taskTextView=(TextView)parent.findViewById(R.id.BtnComplete);
// Log.e("String",(String) taskTextView.getText());
//
this is My IntDatabaseHandler file
package com.example.joelg.clapp;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.iutputStream;
import java.util.ArrayList;
/**
* Created by joelg on 22/10/2017.
*/
public class IntDataBaseHelper extends SQLiteOpenHelper{
private static String DB_PATH ="/data/data/com.example.joelg.clapp/databases";
public static String DB_NAME = "JobList";
public static String DB_COLUMN = "jobNM";
public static String DB_TABLE = "job";
private static String DB_JOB_DETAILS = "jobDetails";
private static String DB_ISDONE = "jobIsDone";
public Context jobContext;
private SQLiteDatabase JobListDatabase;
/**
* constructor t
*/
public IntDataBaseHelper (Context context) {
super (context, DB_NAME,null, 1);
this.jobContext = context;
DB_PATH = jobContext.getDatabasePath(DB_NAME).getPath();
}
public void openDataBase() {
// open the database
String JobListPath = DB_PATH;
JobListDatabase = SQLiteDatabase.openDatabase(JobListPath,null,SQLiteDatabase.OPEN_READONLY);
}
// Getting Job Count
public ArrayList<String> getJobList() {
ArrayList<String> JobList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DB_TABLE,new String[]
{DB_COLUMN},null,null,null,null,null);
while(cursor.moveToNext()){
int index = cursor.getColumnIndex(DB_COLUMN);
JobList.add(cursor.getString(index));
}
cursor.close();
db.close();
return JobList;
}
// Gets the job state if it has been competed or not
public ArrayList<String> getIsDone() {
ArrayList<String> IsDone = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DB_TABLE,new String[]{DB_ISDONE},null,null,null,null,null);
while(cursor.moveToNext()){
int index = cursor.getColumnIndex(DB_ISDONE);
IsDone.add(cursor.getString(index));
}
cursor.close();
db.close();
return IsDone;
}
@override
public synchronized void close(){
if(JobListDatabase !=null){
JobListDatabase.close();
super.close();
}
}
@override
public void onCreate(SQLiteDatabase db) {
}
@override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
CopyDBFromAssets
package com.example.joelg.clapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.iutputStream;
/**
* Created by joelg on 24/10/2017.
*/
public class CopyDBFromAssets {
boolean copied = false;
public static boolean createDataBase(Context context, String databasename) {
boolean copied = false;
boolean dbExist = checkDataBase(context, databasename);
if (!dbExist) {
// calling this method will create an empty database
// which will hopefully be overidden, if not then
// empty database will exist ?????????
//this.getReadableDatabase(); <<<<< NOTE Commented out as empty db with no tables is useless
if (!checkAssetExists(context, databasename, "")) {
Log.e("CREATEDB", "Error getting asset " + databasename);
} else {
return copyDataBase(context, databasename);
}
return false;
}
return true;
}
private static boolean checkAssetExists(Context context, String assetfile, String path) {
boolean rv = false; // assume asset file doesn't exist
String[] assetsfound = new String[]{};
// Get the list of assets at the given path
try {
assetsfound = context.getAssets().list(path);
} catch (IOException e) {
Log.e("CHECKASSET", "IO Exception when checking for the asset file." + e.getMessage());
return false;
}
// Check to see if the desired asset (passed assetfile) exists
for (String s : assetsfound) {
if (s.equals(assetfile)) {
rv = true;
break;
}
}
if (rv) {
Log.d("CHECKASSET", "Asset " + assetfile + "was found.");
} else {
String assetlist = "";
for (String s : assetsfound) {
assetlist = assetlist + " " + s;
}
Log.e("CHECKASSET", "Asset " + assetfile +
"could not be found. Assets that exists are:- " +
assetlist
);
}
// Asset not found lets try ignoring case
if (!rv) {
for (String s : assetsfound) {
if ((s.toLowerCase()).equals(assetfile.toLowerCase())) {
Log.e("CHECKASSET", "Found asset as " + assetfile +
" but looking for " + s +
", although they are similar the case is different."
);
}
}
}
return rv;
}
// check if database exists to avoid recopying it
private static boolean checkDataBase(Context context, String database) {
SQLiteDatabase checkDB = null;
String dbpath = context.getDatabasePath(database).getPath();
try {
checkDB = SQLiteDatabase.openDatabase(dbpath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database doesnt exist yet
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
// copies db from local assets file, were it can be accessed and handled
private static boolean copyDataBase(Context context, String databasename) {
InputStream asset;
OutputStream db;
int bytescopied = 0;
int length_read;
int buffersize = 16384;
int blockcount = 0;
boolean rv = false;
try {
asset = context.getAssets().open(databasename);
} catch (IOException e) {
Log.e("COPYDB",
"IO Error opening the asset " +
databasename +
". Error Message was " +
e.getMessage()
);
return false;
}
try {
db = new FileOutputStream(context.getDatabasePath(databasename).getPath());
} catch (IOException e) {
Log.e("COPYDB",
"IO Error opening the output file for the database with path " +
databasename +
". error Message was " +
e.getMessage()
);
try {
asset.close();
} catch (IOException e2) {
Log.e("COPYDB",
"IO Error closing the asset. Message was " + e2.getMessage()
);
}
return false;
}
byte[] buffer = new byte[buffersize];
try {
while ((length_read = asset.read(buffer)) > 0) {
db.write(buffer);
bytescopied = bytescopied + length_read;
blockcount++;
rv = true;
}
} catch (IOException e) {
Log.e("COPYDB",
"IO Error Copying Database. Bytes Copied = "
+ bytescopied +
" in " +
blockcount +
" blocks of " +
buffersize
);
}
Log.d("COPYDB", "Succesfully copied Database " + databasename + " from the assets." +
" Number of bytes copied = " + bytescopied +
" in " + blockcount + " blocks of length " + buffersize
);
try {
db.flush();
db.close();
asset.close();
} catch (IOException e) {
Log.e("COPYDB",
"IO Error flushing or closing Database or closing asset."
);
}
return rv;
}
}

How to set right the file path for reading, after selecting the file with file picker in android?

In the below attached code , I am able to select file from internal storage using file picker, but unable to open the file for reading the file. code for reading the file is written, looks like its not picking the right path for opening the file, so throwing exception. Can anyone help me diagnose the issue.
package android.ble.internal_storage;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.iutputStreamWriter;
public class MainActivity extends Activity {
private static final int PERMISSION_WRITE_STORAGE = 11;
private static final int PERMISSION_READ_EXTERNAL_STORAGE = 12;
private static final int CHOOSE_TXT_FROM_DEVICE = 1;
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg = (EditText) findViewById(R.id.editText1);
}
public void WriteBtn(View v) {
try {
FileOutputStream fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE); //mytextfile.txt
OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
Context context = getApplicationContext();
String folder = context.getFilesDir().getAbsolutePath();
outputWriter.write(folder + " ");
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_TXT_FROM_DEVICE && resultCode == Activity.RESULT_OK) {
if (data != null) {
Read_from_file(data.getData().getPath());
}
}
}
public void ReadBtn(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, CHOOSE_TXT_FROM_DEVICE);
}
public void Read_from_file(String file_path) {
File fileMedia = new File(file_path);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_WRITE_STORAGE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, PERMISSION_READ_EXTERNAL_STORAGE);
}
try {
FileInputStream fileIn = openFileInput(fileMedia.getName());
InputStreamReader InputRead = new InputStreamReader(fileIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = InputRead.read(inputBuffer)) > 0) {
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
You didn't attach anything. You could also just post a snippet:
[code]in.read(buf);[/code]
Renate said:
You didn't attach anything. You could also just post a snippet:
Code:
in.read(buf);
Click to expand...
Click to collapse
I have pasted the code...
Please use [code="java"] [/code] markup syntax. I can't read gobble-dee-gook.
Spoiler: Original code
Java:
package android.ble.internal_storage;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
private static final int PERMISSION_WRITE_STORAGE = 11;
private static final int PERMISSION_READ_EXTERNAL_STORAGE = 12;
private static final int CHOOSE_TXT_FROM_DEVICE = 1;
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg = (EditText) findViewById(R.id.editText1);
}
public void WriteBtn(View v) {
try {
FileOutputStream fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE); //mytextfile.txt
OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
Context context = getApplicationContext();
String folder = context.getFilesDir().getAbsolutePath();
outputWriter.write(folder + " ");
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_TXT_FROM_DEVICE && resultCode == Activity.RESULT_OK) {
if (data != null) {
Read_from_file(data.getData().getPath());
}
}
}
public void ReadBtn(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, CHOOSE_TXT_FROM_DEVICE);
}
public void Read_from_file(String file_path) {
File fileMedia = new File(file_path);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_WRITE_STORAGE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, PERMISSION_READ_EXTERNAL_STORAGE);
}
try {
FileInputStream fileIn = openFileInput(fileMedia.getName());
InputStreamReader InputRead = new InputStreamReader(fileIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = InputRead.read(inputBuffer)) > 0) {
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem is that your intent.getData() is returning a content URI, not a file URI. There is no path.
https://developer.android.com/reference/android/content/Intent#ACTION_GET_CONTENT
https://developer.android.com/reference/android/content/ContentResolver#openInputStream(android.net.Uri)
Java:
Uri uri = intent.getData();
ContentResolver cr = getContentResolver();
InputStream in = cr.openInputStream(uri);
Renate said:
Please use
Java:
markup syntax. I can't read gobble-dee-gook.
Spoiler: Original code
Java:
package android.ble.internal_storage;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
private static final int PERMISSION_WRITE_STORAGE = 11;
private static final int PERMISSION_READ_EXTERNAL_STORAGE = 12;
private static final int CHOOSE_TXT_FROM_DEVICE = 1;
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg = (EditText) findViewById(R.id.editText1);
}
public void WriteBtn(View v) {
try {
FileOutputStream fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE); //mytextfile.txt
OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
Context context = getApplicationContext();
String folder = context.getFilesDir().getAbsolutePath();
outputWriter.write(folder + " ");
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_TXT_FROM_DEVICE && resultCode == Activity.RESULT_OK) {
if (data != null) {
Read_from_file(data.getData().getPath());
}
}
}
public void ReadBtn(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, CHOOSE_TXT_FROM_DEVICE);
}
public void Read_from_file(String file_path) {
File fileMedia = new File(file_path);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_WRITE_STORAGE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, PERMISSION_READ_EXTERNAL_STORAGE);
}
try {
FileInputStream fileIn = openFileInput(fileMedia.getName());
InputStreamReader InputRead = new InputStreamReader(fileIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = InputRead.read(inputBuffer)) > 0) {
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem is that your intent.getData() is returning a content URI, not a file URI. There is no path.
https://developer.android.com/reference/android/content/Intent#ACTION_GET_CONTENT
https://developer.android.com/reference/android/content/ContentResolver#openInputStream(android.net.Uri)
Java:
Uri uri = intent.getData();
ContentResolver cr = getContentResolver();
InputStream in = cr.openInputStream(uri);
Click to expand...
Click to collapse
Thank you so much for your help now code is working

Categories

Resources