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;
}
}
Related
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
Hi there,
I am writing an app and for one of the features I need the firmware build number.
I know I can get the firmware version(like 4.1.1) with android.os.build but I need the build number of a rom(like "Rom version 1.0") thats stored in build.prop. I know I can parse the whole build.prop file and extract the 1 string of information but is there another way to get is faster and that it doesnt require root to use?
Grtz,
Thirith
Solved it
I solved my own question
Here is how I did it(in case somebody wants to achieve the same thing):
Code:
TextView tv = (TextView)findViewById(R.id.text1);
String input = "getprop |awk -F : '/build.display.id/ { print $2 }'";
execCommandLine(input, tv);
void execCommandLine(String command, TextView tv)
{
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
// Running the Script
try
{
proc = runtime.exec("su");
osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(command);
osw.flush();
osw.close();
}
// If return error
catch (IOException ex)
{
// Log error
Log.e("execCommandLine()", "Command resulted in an IO Exception: " + command);
return;
}
// Try to close the process
finally
{
if (osw != null)
{
try
{
osw.close();
}
catch (IOException e){}
}
}
try
{
proc.waitFor();
}
catch (InterruptedException e){}
// Display on screen if error
if (proc.exitValue() != 0)
{
Log.e("execCommandLine()", "Command returned error: " + command + "\n Exit code: " + proc.exitValue());
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(command + "\nWas not executed sucessfully!");
builder.setNeutralButton("OK", null);
AlertDialog dialog = builder.create();
dialog.setTitle("Script Error");
dialog.show();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
try {
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String exit = output.toString();
if(exit != null && exit.length() == 0) {
exit = "Command executed Successfully but no output was generated";
}
tv.setText(exit);
}
Hi, thanks for making your code public!
Just got an error when trying your code into my app.
Line
Code:
execCommandLine(input, tv);
runs into this error:
Multiple markers at this line
- input cannot be resolved to a type
- Return type for the method is missing
- Syntax error on token ",", delete this
token
Click to expand...
Click to collapse
How do I fix it?
Ok, did a mistake with integrating the code. My whole activity:
Code:
package de.yanniks.cm_updatechecker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import de.yanniks.cm_updatechecker.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class UpdateChecker extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatecheck);
TextView tv = (TextView)findViewById(R.id.installedversion);
String input = "getprop |awk -F : '/build.display.id/ { print $2 }'";
execCommandLine(input, tv);}
void execCommandLine(String command, TextView tv)
{
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
// Running the Script
try
{
proc = runtime.exec("su");
osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(command);
osw.flush();
osw.close();
}
// If return error
catch (IOException ex)
{
// Log error
Log.e("execCommandLine()", "Command resulted in an IO Exception: " + command);
return;
}
// Try to close the process
finally
{
if (osw != null)
{
try
{
osw.close();
}
catch (IOException e){}
}
}
try
{
proc.waitFor();
}
catch (InterruptedException e){}
// Display on screen if error
if (proc.exitValue() != 0)
{
Log.e("execCommandLine()", "Command returned error: " + command + "\n Exit code: " + proc.exitValue());
AlertDialog.Builder builder = new AlertDialog.Builder(UpdateChecker.this);
builder.setMessage(command + "\nWas not executed sucessfully!");
builder.setNeutralButton("OK", null);
AlertDialog dialog = builder.create();
dialog.setTitle("Script Error");
dialog.show();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
try {
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String exit = output.toString();
if(exit != null && exit.length() == 0) {
exit = "Command executed Successfully but no output was generated";
}
tv.setText(exit);
}
}
A better solution is to use my SystemProperties.get("build.display.id") directly instead of forking a native binary.
Code:
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class SystemProperties {
public static final int PROP_NAME_MAX= 32; // sic
public static final int PROP_VALUE_MAX= 92; // sic
public static final int PROP_AREA_MAGIC= 0x504f5250; // "PROP"
public static final int PROP_AREA_VERSION= 0x45434f76; // "vOCE" (API level 3..8 at least)
public static final String PROP_SERVICE_NAME= "property_service";
public static final String WORKSPACE= "ANDROID_PROPERTY_WORKSPACE";
// prop_area struct
public static final int PA_COUNT= 0;
public static final int PA_SERIAL= 4;
public static final int PA_MAGIC= 8;
public static final int PA_VERSION= 12;
public static final int PA_RESERVED= 16;
public static final int PA_TOC= 32;
public static final int PA_INFO_NAME= 0;
public static final int PA_INFO_SERIAL= PA_INFO_NAME+PROP_NAME_MAX;
public static final int PA_INFO_VALUE= PA_INFO_SERIAL+4;
private static MappedByteBuffer mMap= null;
private static boolean init() throws IllegalArgumentException,
SecurityException,
NoSuchFieldException,
IllegalAccessException,
IOException {
FileDescriptor fd;
MappedByteBuffer mbb= null;
String workspace= System.getenv(WORKSPACE);
if (workspace == null) {
throw new IllegalArgumentException(WORKSPACE + " not set");
}
String[] wsArray= workspace.split(",");
int osFd= 0;
int len= 0;
try {
osFd= new Integer(wsArray[0]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(e.getMessage());
}
try {
len= new Integer(wsArray[1]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(e.getMessage());
}
//Log.i(TAG, "Read fd " + Integer.toString(osFd) + " for " + len + " bytes.");
fd= new FileDescriptor();
Class<?> c= fd.getClass();
Field f= c.getDeclaredField("descriptor");
f.setAccessible(true);
f.setInt(fd, osFd);
FileInputStream in= new FileInputStream(fd);
FileChannel fc= in.getChannel();
mbb= fc.map(FileChannel.MapMode.READ_ONLY, 0, len);
mbb.order(ByteOrder.LITTLE_ENDIAN);
if (mbb.getInt(PA_MAGIC) != PROP_AREA_MAGIC) {
throw new IllegalArgumentException("Wrong kind of magic " + Integer.toString(mbb.getInt(PA_MAGIC), 16));
}
if (mbb.getInt(PA_VERSION) != PROP_AREA_VERSION) {
throw new IllegalArgumentException("Incorrect version " + Integer.toString(mbb.getInt(PA_VERSION), 16));
}
mMap= mbb;
return(true);
}
public static String get(String key) throws IllegalArgumentException,
SecurityException,
NoSuchFieldException,
IllegalAccessException,
IOException {
if (mMap == null) {
if (!init())
return(null);
}
int index= property_find(key);
//Log.i(TAG, "Found entry at " + Integer.toString(index));
if (index < 0)
return(null);
return(getString(index+PA_INFO_VALUE));
}
private static int property_find(String name) {
int count= mMap.getInt(PA_COUNT);
int tok= -1;
//Log.i(TAG, "Key " + name);
next: while(count-- > 0) {
tok++;
int entry= mMap.getInt(PA_TOC + tok*4);
//Log.i(TAG, "Entry " + tok + ": " + Integer.toString(entry, 16));
if ((entry >> 24) != name.length())
continue;
int index= (entry & 0xFFFFFF);
//Log.i(TAG, "Index " + index);
for (int i=0; i<name.length(); i++) {
//Log.i(TAG, "Cmp(" + entry + ":" + index + ":" + i + "): " + (char)(mbb.get(index+i)) + " -- " + name.charAt(i));
if ((char)(mMap.get(index+i)) != name.charAt(i)) {
continue next;
}
}
// found
return(index);
}
return(-1);
}
private static String getString(int index) {
byte b[]= new byte[PROP_VALUE_MAX];
int i= 0;
do {
b[i]= mMap.get(i+index);
} while (b[i++] != 0);
return(new String(b, 0, i-1));
}
}
Sorry 'bout the terrible indentation. Cut'n'paste isn't my code's best friend, obviously.
Hi
I'm build an android application using WebNMS library that apply snmp get operation on router but the result is null and this is the error message
"Error Sending PDU. IO error sending PDU. Send Error: null"
this is my code :
Code:
package com.example.snmptst;
import com.adventnet.snmp.beans.SnmpTarget;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SnmpTarget target;
String targetHost;
int targetPort;
String community;
int timeout;
int retries;
String returnString = null;
targetHost = "192.168.1.1";
targetPort = 161;
community = "public";
timeout = 5000;
retries = 2;
// Use an SNMP target bean to perform SNMP operations
target = new SnmpTarget();
target.setTargetHost(targetHost); // set the agent hostname
if(community != null) { // set the community if specified
target.setCommunity(community);
}
target.setTargetPort(targetPort); // set the port, default is 161
// set the timeout/retries parameters, default are 5 and 0
target.setTimeout(timeout);
target.setRetries(retries);
// Create oidList array from the obtained arrayList
String []oidList = new String[1];
oidList[0]=".1.3.6.1.2.1.1.5.0";
// Set the OID List on the SnmpTarget instance
target.setObjectIDList(oidList);
String[] result = target.snmpGetList(); // do a get request
// Return the result/error from the response.
if(result != null) {
String successString = "Response received. Values:\n"; //No I18N
for(int k=0; k<result.length; k++) {
successString = successString + target.getObjectID(k) + " : " + result[k] + "\n"; //No I18N
}
returnString = successString;
} else {
String errorString = "Request Failed or Timed-out. \n"; //No I18N
errorString = errorString + target.getErrorString();
returnString = errorString;
}
Toast.makeText(getApplicationContext(), returnString, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Any one can help me?
Thanks.
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);
}
}
Hey all, i want to make an android app which presents a form which sends the data inserted in a database when the submit button is pressed..im a newbie but i think i ve got some progress here. i present my code:
package com.example.marialena.practice;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_LAST_NAME = "last_name";
private static final String KEY_ORIGIN = "origin";
public DatabaseHandler(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}
// Creating Tables
@override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_LAST_NAME + " TEXT," + KEY_ORIGIN + "TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_LAST_NAME, contact.getLastName()); // Contact last Name
values.put(KEY_ORIGIN, contact.getOrigin()); // Contact Origin
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_LAST_NAME, KEY_ORIGIN }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setLastName(cursor.getString(2));
contact.setOrigin(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_LAST_NAME, contact.getLastName());
values.put(KEY_ORIGIN, contact.getOrigin());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
DisplayMessageActivity.java
package com.example.marialena.practice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.List;
public class DisplayMessageActivity extends MyActivity {
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//receiving data
Intent intent = getIntent();
//manipulating message extraction and thank u message.
String message = "Thank You!";
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "Alonso","HollowStr"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Last Name: " + cn.getLastName() + " ,Origin: " + cn.getOrigin();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyActivity.java
package com.example.marialena.practice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.marialena.practice.MESSAGE";
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my, menu);
return true;
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.name);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
/* Intent intent2 = new Intent(this, DisplayMessageActivity.class);
EditText editText2 = (EditText) findViewById(R.id.last);
String message2 = editText2.getText().toString();
intent2.putExtra(EXTRA_MESSAGE, message2);
startActivity(intent2);*/
}
}
CONTACT.JAVA
package com.example.marialena.practice;
/**
* Created by Marialena on 7/31/2015.
*/
public class Contact {
//private variables
int _id;
String _name;
String _last_name;
String _origin;
//empty constructor
public Contact(){}
//constructor plus ID
public Contact(int id,String name, String last_name, String origin){
this._id=id;
this._last_name=last_name;
this._name=name;
this._origin=origin;
}
//constructor simple
public Contact(String name, String last_name, String origin){
this._origin=origin;
this._name=name;
this._last_name=last_name;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting last name
public String getLastName(){
return this._last_name;
}
// setting last name
public void setLastName(String last_name){
this._last_name = last_name;
}
// getting origin
public String getOrigin(){
return this._origin;
}
// setting origin
public void setOrigin(String origin){
this._origin = origin;
}
}
nikoc03 said:
Hey all, i want to make an android app which presents a form which sends the data inserted in a database when the submit button is pressed..im a newbie but i think i ve got some progress here. i present my code:
package com.example.marialena.practice;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_LAST_NAME = "last_name";
private static final String KEY_ORIGIN = "origin";
public DatabaseHandler(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}
// Creating Tables
@override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_LAST_NAME + " TEXT," + KEY_ORIGIN + "TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_LAST_NAME, contact.getLastName()); // Contact last Name
values.put(KEY_ORIGIN, contact.getOrigin()); // Contact Origin
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_LAST_NAME, KEY_ORIGIN }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setLastName(cursor.getString(2));
contact.setOrigin(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_LAST_NAME, contact.getLastName());
values.put(KEY_ORIGIN, contact.getOrigin());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
DisplayMessageActivity.java
package com.example.marialena.practice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.List;
public class DisplayMessageActivity extends MyActivity {
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//receiving data
Intent intent = getIntent();
//manipulating message extraction and thank u message.
String message = "Thank You!";
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "Alonso","HollowStr"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Last Name: " + cn.getLastName() + " ,Origin: " + cn.getOrigin();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyActivity.java
package com.example.marialena.practice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.marialena.practice.MESSAGE";
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my, menu);
return true;
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.name);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
/* Intent intent2 = new Intent(this, DisplayMessageActivity.class);
EditText editText2 = (EditText) findViewById(R.id.last);
String message2 = editText2.getText().toString();
intent2.putExtra(EXTRA_MESSAGE, message2);
startActivity(intent2);*/
}
}
CONTACT.JAVA
package com.example.marialena.practice;
/**
* Created by Marialena on 7/31/2015.
*/
public class Contact {
//private variables
int _id;
String _name;
String _last_name;
String _origin;
//empty constructor
public Contact(){}
//constructor plus ID
public Contact(int id,String name, String last_name, String origin){
this._id=id;
this._last_name=last_name;
this._name=name;
this._origin=origin;
}
//constructor simple
public Contact(String name, String last_name, String origin){
this._origin=origin;
this._name=name;
this._last_name=last_name;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting last name
public String getLastName(){
return this._last_name;
}
// setting last name
public void setLastName(String last_name){
this._last_name = last_name;
}
// getting origin
public String getOrigin(){
return this._origin;
}
// setting origin
public void setOrigin(String origin){
this._origin = origin;
}
}
Click to expand...
Click to collapse
I suggest starting here:
http://forum.xda-developers.com/app-development