I'm working on a proof-of-concept app so that I can implement the feature in a larger app I'm making. I'm a bit new to Java and Android Dev but hopefully this shouldn't be too simple or complex of a question.
Basically, I'm trying to read in a list of strings from a CSV file and make it usable in displaying the list on the app's Main Activity.
I'm using an external class for reading in CSV's. Here's the class code:
CSVFile.java
package com.yourtechwhiz.listdisplay;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream){
this.inputStream = inputStream;
}
public List read(){
List resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
Log.d("VariableTag", row[0].toString());
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
Here's my main activity code:
MainActivity.java
package com.yourtechwhiz.listdisplay;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// Array of strings that's used to display on screen
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
"WebOS","Ubuntu","Windows7","Max OS X"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prepArray();
//Display List on Activity
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, mobileArray);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
}
//Get list of strings from CSV ready to use
private void prepArray() {
InputStream inputStream = getResources().openRawResource(R.raw.strings);
CSVFile csvFile = new CSVFile(inputStream);
List myList = csvFile.read();
//This is where it has an error
//Set first array in myList to this new array myArray
String[] myArray = myList.get(0);
}
}
I'm not actually to the point of setting the mobileArray array yet. Right now I'm just trying to "extract" the information out of the List object myList...
Can someone explain to me how this is done? Maybe I'm just not understanding the List type completely. It seems like when resultList is returned in the CSVFile read method, it's returned as an List object consisting of String array objects. But I can't seem to get it to work like that.
Any help is appreciated!
FINAL EDIT (working code)
private void prepArray() {
try{
CSVReader reader = new CSVReader(new InputStreamReader(getResources().openRawResource(R.raw.strings)));//Specify asset file name
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
Log.d("VariableTag", nextLine[0]);
}
}catch(Exception e){
e.printStackTrace();
Toast.makeText(this, "The specified file was not found", Toast.LENGTH_SHORT).show();
}
}
EDIT
Now my prepArray function looks like the following:
private void prepArray() {
try{
String csvfileString = this.getApplicationInfo().dataDir + File.separatorChar + "strings.csv"
File csvfile = new File(csvfileString);
CSVReader reader = new CSVReader(new FileReader("csvfile.getAbsolutePath()"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
}catch(FileNotFoundException e){
e.printStackTrace();
Toast.makeText(this, "The specified file was not found", Toast.LENGTH_SHORT).show();
}
}
Still produces the FileNotFoundException.
EDIT 2/3
Here's the log that's produced when I run the app on an actual phone with the strings.csv in a subfolder of strings (src\main\assets\strings\strings.csv) with the change you requested to the code:
03/27 17:44:01: Launching app
$ adb push C:\Users\Roy\AndroidStudioProjects\ListDisplay\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.yourtechwhiz.listdisplay
$ adb shell pm install -r "/data/local/tmp/com.yourtechwhiz.listdisplay"
pkg: /data/local/tmp/com.yourtechwhiz.listdisplay
Success
$ adb shell am start -n "com.yourtechwhiz.listdisplay/com.yourtechwhiz.listdisplay.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Connecting to com.yourtechwhiz.listdisplay
D/HyLog: I : /data/font/config/sfconfig.dat, No such file or directory (2)
D/HyLog: I : /data/font/config/dfactpre.dat, No such file or directory (2)
D/HyLog: I : /data/font/config/sfconfig.dat, No such file or directory (2)
W/ActivityThread: Application com.yourtechwhiz.listdisplay is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/dalvikvm: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8609', transport: 'socket'
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1498)
I/dalvikvm: Could not find method android.view.Window$Callback.onProvideKeyboardShortcuts, referenced from method android.support.v7.view.WindowCallbackWrapper.onProvideKeyboardShortcuts
W/dalvikvm: VFY: unable to resolve interface method 16152: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V
D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
W/dalvikvm: VFY: unable to resolve interface method 16154: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
W/dalvikvm: VFY: unable to resolve interface method 16158: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
W/dalvikvm: VFY: unable to resolve virtual method 455: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
W/dalvikvm: VFY: unable to resolve virtual method 477: Landroid/content/res/TypedArray;.getType (I)I
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0008
I/dalvikvm: Could not find method android.widget.FrameLayout.startActionModeForChild, referenced from method android.support.v7.widget.ActionBarContainer.startActionModeForChild
W/dalvikvm: VFY: unable to resolve virtual method 16589: Landroid/widget/FrameLayout;.startActionModeForChild (Landroid/view/View;Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002
I/dalvikvm: Could not find method android.content.Context.getColorStateList, referenced from method android.support.v7.content.res.AppCompatResources.getColorStateList
W/dalvikvm: VFY: unable to resolve virtual method 269: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
W/dalvikvm: VFY: unable to resolve virtual method 418: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
W/dalvikvm: VFY: unable to resolve virtual method 420: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
W/dalvikvm: VFY: unable to resolve instanceof 140 (Landroid/graphics/drawable/RippleDrawable;) in Landroid/support/v7/widget/AppCompatImageHelper;
D/dalvikvm: VFY: replacing opcode 0x20 at 0x000c
W/System.err: java.io.FileNotFoundException: /csvfile.getAbsolutePath(): open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:462)
W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:78)
W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:105)
W/System.err: at java.io.FileReader.<init>(FileReader.java:66)
W/System.err: at com.yourtechwhiz.listdisplay.MainActivity.prepArray(MainActivity.java:43)
W/System.err: at com.yourtechwhiz.listdisplay.MainActivity.onCreate(MainActivity.java:26)
W/System.err: at android.app.Activity.performCreate(Activity.java:5287)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2145)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2231)
W/System.err: at android.app.ActivityThread.access$700(ActivityThread.java:139)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1401)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:137)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5082)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:598)
W/System.err: at dalvik.system.NativeStart.main(Native Method)
W/System.err: Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.Posix.open(Native Method)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:446)
W/System.err: ... 19 more
I/Adreno-EGL: <qeglDrvAPI_eglInitialize:385>: EGL 1.4 QUALCOMM build: ()
OpenGL ES Shader Compiler Version: E031.24.00.01
Build Date: 12/27/13 Fri
Local Branch: qualcomm_only
Remote Branch:
Local Patches:
Reconstruct Branch:
D/OpenGLRenderer: Enabling debug mode 0
D/OpenGLRenderer: GL error from OpenGLRenderer: 0x502
E/OpenGLRenderer: GL_INVALID_OPERATION
Try OpenCSV - it will make your life easier.
First, add this package to your gradle dependencies as follows
implementation 'com.opencsv:opencsv:4.6'
Then you can either do
import com.opencsv.CSVReader;
import java.io.IOException;
import java.io.FileReader;
...
try {
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
} catch (IOException e) {
}
or
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();
Edit after comment
try {
File csvfile = new File(Environment.getExternalStorageDirectory() + "/csvfile.csv");
CSVReader reader = new CSVReader(new FileReader(csvfile.getAbsolutePath()));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "The specified file was not found", Toast.LENGTH_SHORT).show();
}
If you want to package the .csv file with the application and have it install on the internal storage when the app installs, create an assets folder in your project src/main folder (e.g., c:\myapp\app\src\main\assets\), and put the .csv file in there, then reference it like this in your activity:
String csvfileString = this.getApplicationInfo().dataDir + File.separatorChar + "csvfile.csv"
File csvfile = new File(csvfileString);
The following snippet reads a CSV file from the raw resources folder (which will be packed into your .apk file upon compilation).
Android by default does not create the raw folder. Create a raw folder under res/raw in your project and copy your CSV File into it. Keep the name of the CSV file lower case and convert it into text format when asked. My CSV file name is welldata.csv.
In the snippet, WellData is the model class (with constructor, getter and setter) and wellDataList is the ArrayList to store the data.
private void readData() {
InputStream is = getResources().openRawResource(R.raw.welldata);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
try {
while ((line = reader.readLine()) != null) {
// Split the line into different tokens (using the comma as a separator).
String[] tokens = line.split(",");
// Read the data and store it in the WellData POJO.
WellData wellData = new WellData();
wellData.setOwner(tokens[0]);
wellData.setApi(tokens[1]);
wellData.setLongitude(tokens[2]);
wellData.setLatitude(tokens[3]);
wellData.setProperty(tokens[4]);
wellData.setWellName(tokens[5]);
wellDataList.add(wellData);
Log.d("MainActivity" ,"Just Created " + wellData);
}
} catch (IOException e1) {
Log.e("MainActivity", "Error" + line, e1);
e1.printStackTrace();
}
}
This worked for me in Kotlin. You will need to place the myfile.csv file in the res/raw folder, creating the folder if it isn't there.
val inputStream: InputStream = resources.openRawResource(R.raw.myfile)
val reader = BufferedReader(InputStreamReader(inputStream, Charset.forName("UTF-8")))
reader.readLines().forEach {
//get a string array of all items in this line
val items = it.split(",")
//do what you want with each item
}
New coder for Android Studio. I've been researching how to read CSV files and this works best for my needs. (s0, s1, etc. Strings were defined at the beginning of my program).
File fileDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File fileToGet = new File(fileDirectory,"aFileName.csv");
try {
BufferedReader br = new BufferedReader(new FileReader(fileToGet));
String line;
while ((line = br.readLine()) !=null) {
String[] tokens = line.split(",");
s0=tokens[0].toString(); s1=tokens[1].toString(); s2=tokens[2].toString();
s3=tokens[3].toString(); s4=tokens[4].toString(); s5=tokens[5].toString();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Here is a simple way, which worked for me.
MainActivity.java
// Do not forget to call readWeatherData() in onCreate or wherever you need to :)
// Defining ordered collection as WeatherSample class
private List<WeatherSample> weatherSamples = new ArrayList<>();
private void readWeatherData() {
// Read the raw csv file
InputStream is = getResources().openRawResource(R.raw.data);
// Reads text from character-input stream, buffering characters for efficient reading
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
// Initialization
String line = "";
// Initialization
try {
// Step over headers
reader.readLine();
// If buffer is not empty
while ((line = reader.readLine()) != null) {
Log.d("MyActivity","Line: " + line);
// use comma as separator columns of CSV
String[] tokens = line.split(",");
// Read the data
WeatherSample sample = new WeatherSample();
// Setters
sample.setMonth(tokens[0]);
sample.setRainfall(Double.parseDouble(tokens[1]));
sample.setSumHours(Integer.parseInt(tokens[2]));
// Adding object to a class
weatherSamples.add(sample);
// Log the object
Log.d("My Activity", "Just created: " + sample);
}
} catch (IOException e) {
// Logs error with priority level
Log.wtf("MyActivity", "Error reading data file on line" + line, e);
// Prints throwable details
e.printStackTrace();
}
}
WeatherSample.java
public class WeatherSample {
private String month;
private double rainfall;
private int sumHours;
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public double getRainfall() {
return rainfall;
}
public void setRainfall(double rainfall) {
this.rainfall = rainfall;
}
public int getSumHours() {
return sumHours;
}
public void setSumHours(int sumHours) {
this.sumHours = sumHours;
}
#Override
public String toString() {
return "WeatherSample{" +
"month='" + month + '\'' +
", rainfall=" + rainfall +
", sumHours=" + sumHours +
'}';
}
}
As for your source CSV file, first create directory:
app -> res (Right click) -> New -> Android resource directory -> Resource type (raw) -> OK
Then copy and paste your .csv file into that newly appeared directory:
raw (Right click) -> Show in Explorer
Here is the source file I used for the project:
data.csv
If you still have some error, here is a link to the full project:
Source Code
Hope it helps, have fun :)
With a file named filename.csv in the folder res/raw:
private void gettingItemsFromCSV() {
BufferedInputStream bufferedInputStream = new BufferedInputStream(getResources().openRawResource(R.raw.filename));
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(bufferedInputStream));
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.i("Test123", line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
In the latest Android 11 version, you need to do something like this:
val reader = CSVReader(
getApplication<Application>().applicationContext.assets.open("file-name.csv")
.reader()
)
val myEntries: List<Array<String>> = reader.readAll()
In build.gradle(app level):
dependencies {
...
// CSV reader
implementation 'com.opencsv:opencsv:4.6'
}
In AndroidManifest.xml:
<application
android:requestLegacyExternalStorage="true"
...
Related
I'm about to go nuts with this. I keep getting errors when trying to open a text file that's in my assets directory, whose full path name is
C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\
app\src\main\assets
Even though we can SEE filename Dictionary.dic in the assets folder for my project...
... I keep getting errors that the file doesn't exist:
W/`````: Can't open <Dictionary.dic>
W/System.err: java.io.FileNotFoundException: Dictionary.dic
W/System.err: at android.content.res.AssetManager.openAsset(Native Method)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:328)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:315)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:841)
Doc says you can use hierarchical name in the open statement:
W/`````: Can't open <C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic>
W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic
W/System.err: at android.content.res.AssetManager.openAsset(Native Method)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:330)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:317)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
Same problem.
Can you see any problem with my code? The problem HAS to be obvious, but after two days of trying this and that and utterly failing, and it LOOKS so good and therefore MUST be obvious, but I CAN'T SEE IT....
I've included this in case it's not obvious from above. If this doesn't help, I'm on my own.
Here is how DatabaseConnector gets called in onCreate in MainActivity:
assets = getAssets();
dbc = new DatabaseConnector(getApplicationContext(), assets); // to create DB if needed
Here's how mAssets and SOURCE_NAME are defined; also have DatabaseConnector definition and its call to dbOpenHelper.
Here's how LoadDatabase is called from createDbIfNecessary:
LoadDatabase
__loadDb;
__loadDb = new LoadDatabase();
__loadDb.execute((Object[]) null);
EDIT
Another opinion:
EDIT 2
Please note that changing the filename in the code to lowercase doesn't help. AND it's a DOS file, NOT ANDROID. AND File is never leaving drive C:
public static String DATABASE_SOURCE =
"C:\\Users\\Dov\\Desktop\\ServyHelperton\\app\\src\\main" +
"\\assets\\dictionary.dic";
W/`````: Can't open <C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic>
W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic
I could add more code to prove what I just said, but trust me. The DATABASE_SOURCE name is ALL I changed.
It appears your path is for Dictionary.dic rather than dictionary.dic
See if that helps
In the end, the fix was sort of easy or maybe dumb luck, because I'm not sure why making the InputStream and Scanner local to doInBackground cured the problem.
Refer to the first picture in the original Question. I made no significant changes to MainActivity, but here is the interesting line in it:
dbc = new DatabaseConnector(getApplicationContext(), getAssets());
This is what worked:
public class DatabaseConnector
{
static Context mContext;
public DatabaseConnector(Context _context, AssetManager _assets)
{
mAssets = _assets;
mContext = _context;
mDbOpenHelper = new DbOpenHelper(_context, DATABASE_NAME, null, 1);
createDbIfNecessary();
}
private class DbOpenHelper extends SQLiteOpenHelper
{
DbOpenHelper(Context _context, String _name, CursorFactory _factory, int _version)
{
super(_context, _name, _factory, _version);
}
private class LoadDatabase extends AsyncTask<Object, Integer, Void>
{
protected Void doInBackground(Object[] params)
{
Scanner scDict = null; // ***** MOVING/ADDING THESE
InputStream stream; // ***** TWO LINES HERE WAS KEY
try{
stream = mContext.getAssets().open(DATABASE_SOURCE);
scDict = new Scanner(stream).useDelimiter("\r\n");
}
catch(IOException e){e.printStackTrace(); System.exit(69);}
}
}
}
}
i have a strange logcat message while creating app for Android .I'm calling a webservice and creating a listview in the process. I' m currently using retrofit2 for this.
public ArrayList<AgencyModel> DownloadAgencyData() {
RestApi.getUnicsAgencyApi().getStreams().enqueue(new Callback<ArrayList<AgencyModel>>() {
#Override
public void onFailure(Call<ArrayList<AgencyModel>> arg0, Throwable arg1) {
// TODO Auto-generated method stub
Log.e("Error in parsing", arg0.toString());
}
#Override
public void onResponse(Call<ArrayList<AgencyModel>> AgencyModelData,
Response<ArrayList<AgencyModel>> response) {
// TODO Auto-generated method stub
mstreamData = new ArrayList<AgencyModel>();
// ADD TO List here!!!!!!!!
// Log.e("Response", "" + response.body().size());
if(response.isSuccessful()){
mstreamData.addAll(response.body());
}
}
});
return mstreamData;
}
The builder class is as follows:
public class RestApi {
private static String ENDPOINT_URL = "http://192.168.1.102/UnicsApplication/";
private static UnicsAgencyApi sUnicsAgencyApi;
private static Retrofit retrofit;
public static UnicsAgencyApi getUnicsAgencyApi() {
if (sUnicsAgencyApi == null) {
retrofit = new Retrofit.Builder().baseUrl(ENDPOINT_URL).addConverterFactory(GsonConverterFactory.create())
.build();
sUnicsAgencyApi = retrofit.create(UnicsAgencyApi.class);
}
return sUnicsAgencyApi;
}
public interface UnicsAgencyApi {
//#GET("api/uconnectservice/AllAgency")
#GET("api/uconnectservice")
Call<ArrayList<AgencyModel>> getStreams();
}
}
The Complete logcat message it get is as follows:
01-03 16:55:54.592: W/ResourceType(2794): CREATING STRING CACHE OF 36 bytes
01-03 16:55:54.912: I/ActivityManager(2794): Timeline: Activity_idle id: android.os.BinderProxy#41a364b0 time:190796801
01-03 16:56:06.152: D/LIST STATUS(2794): AgencyList is null
01-03 16:56:06.182: W/dalvikvm(2794): VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
01-03 16:56:06.182: W/dalvikvm(2794): VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
01-03 16:56:06.182: I/dalvikvm(2794): Could not find method java.nio.file.Files.newOutputStream, referenced from method okio.Okio.sink
01-03 16:56:06.182: W/dalvikvm(2794): VFY: unable to resolve static method 3073: Ljava/nio/file/Files;.newOutputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/OutputStream;
01-03 16:56:06.182: D/dalvikvm(2794): VFY: replacing opcode 0x71 at 0x000a
01-03 16:56:06.192: W/dalvikvm(2794): VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
01-03 16:56:06.192: W/dalvikvm(2794): VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
01-03 16:56:06.192: I/dalvikvm(2794): Could not find method java.nio.file.Files.newInputStream, referenced from method okio.Okio.source
01-03 16:56:06.192: W/dalvikvm(2794): VFY: unable to resolve static method 3072: Ljava/nio/file/Files;.newInputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/InputStream;
01-03 16:56:06.192: D/dalvikvm(2794): VFY: replacing opcode 0x71 at 0x000a
01-03 16:56:16.192: E/Error in parsing(2794): retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall#41bdff80
I was hoping anybody could guide or explain why this is happening.
For clarity sake here is my JAVA model
package com.nickSoft.Models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AgencyModel {
#SerializedName("AgencyName")
#Expose
private String agencyName;
#SerializedName("AgencyLocation")
#Expose
private String agencyLocation;
#SerializedName("AgencyPhoneNumber")
#Expose
private String agencyPhoneNumber;
#SerializedName("AgencyGPSCoordinates")
#Expose
private String agencyGPSCoordinates;
#SerializedName("AgencyHours")
#Expose
private String agencyHours;
public String getAgencyName() {
return agencyName;
}
public void setAgencyName(String agencyName) {
this.agencyName = agencyName;
}
public String getAgencyLocation() {
return agencyLocation;
}
public void setAgencyLocation(String agencyLocation) {
this.agencyLocation = agencyLocation;
}
public String getAgencyPhoneNumber() {
return agencyPhoneNumber;
}
public void setAgencyPhoneNumber(String agencyPhoneNumber) {
this.agencyPhoneNumber = agencyPhoneNumber;
}
public String getAgencyGPSCoordinates() {
return agencyGPSCoordinates;
}
public void setAgencyGPSCoordinates(String agencyGPSCoordinates) {
this.agencyGPSCoordinates = agencyGPSCoordinates;
}
public String getAgencyHours() {
return agencyHours;
}
public void setAgencyHours(String agencyHours) {
this.agencyHours = agencyHours;
}
}
and here is the JSON coming in from webservice:
[{"AgencyName":"Head-Office/Branch","AgencyLocation":"Immeuble Grand Carrefour Rue Marie Gocker,Yaounde","AgencyPhoneNumber":"+237222229610/691698762","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Yaounde-Marche-Centrale Branch","AgencyLocation":"Immeuble Grand Carrefour Rue Marie Gocker,Yaounde","AgencyPhoneNumber":"+237222041661/22229604/91697426","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Bamenda Branch","AgencyLocation":"Evidence Building, City Chemist Roundabout,Bamenda","AgencyPhoneNumber":"+237222041665/233364170/691697553","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Deido Branch","AgencyLocation":"Face Boulangerie COAF, Douala","AgencyPhoneNumber":"+237222041660/633402641/691697494","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Bafut Branch","AgencyLocation":"Midland Centre, 3 Corners Njinteh, Bafut","AgencyPhoneNumber":"+237675025263/691698716","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Buea Branch","AgencyLocation":"University Junction, Molyko, Buea","AgencyPhoneNumber":" +237222041664/333323322/691698625","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Bonaberi Branch","AgencyLocation":"Cimetière, Immeuble Pharmacie Bonaberi, Douala","AgencyPhoneNumber":"+237222041663/333392710/691697617","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Biyem-Assi Branch","AgencyLocation":"Carrefour Biyem-assi ,Yaounde","AgencyPhoneNumber":"+237222041662/222316710/691698667","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Limbe Branch","AgencyLocation":"Down Beach, Sappa Road, Limbe","AgencyPhoneNumber":"+237222041690/222041693/691698628","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Kribi Branch","AgencyLocation":"Adjacent Auto Ecole Française Rue Petit Paris, Kribi","AgencyPhoneNumber":"+237222041691/222041692/691698632","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Akwa Branch","AgencyLocation":"Boulevard de la Liberté, Douala","AgencyPhoneNumber":"+237222041670/691698663","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Dakar Branch","AgencyLocation":"Marché Bilongué, Douala","AgencyPhoneNumber":"+237691698627","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Bambili Branch","AgencyLocation":"Three Corners, Bambili","AgencyPhoneNumber":"+237222054199/691697441","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Tchinga Branch","AgencyLocation":"Ave du 27 Août 1940,Yaounde","AgencyPhoneNumber":"691907381","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"},{"AgencyName":"Kumba Branch","AgencyLocation":"Kumba","AgencyPhoneNumber":"+237222041664","AgencyGPSCoordinates":"GPS Position","AgencyHours":"8:00-16:00"}]
Any guidance is greatly appreciated.
So I have been working on this for a bit and hit a brick wall. It keeps giving me a fatal error when it start to process.
So basically I want to read in a text file off the internet and then parse it so I can start to break that apart and use a JSON parser to deal with JSON data. But that further down the line (and i have the part built). I just am having trouble with the connection and downloading of the data. I just want to read in the text file and then print it out again.
Thank you for any help with this.
This is what it gives me
01-26 15:11:48.373 1958-1958/com.example.mmillar.urljsonparser I/art: Not late-enabling -Xcheck:jni (already on)
01-26 15:11:48.556 1958-1958/com.example.mmillar.urljsonparser D/HTML P1:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.556 1958-1958/com.example.mmillar.urljsonparser D/HTML P2:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.557 1958-1958/com.example.mmillar.urljsonparser D/HTML inJSON:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/Status:: Connection Opened
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/Status:: Closing connection
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/AndroidRuntime: Shutting down VM
01-26 15:11:48.570 1958-1958/com.example.mmillar.urljsonparser E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mmillar.urljsonparser, PID: 1958
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mmillar.urljsonparser/com.example.mmillar.urljsonparser.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
at com.example.mmillar.urljsonparser.JSONParser.getStream(JSONParser.java:40)
at com.example.mmillar.urljsonparser.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
01-26 15:11:53.474 1958-1958/? I/Process: Sending signal. PID: 1958 SIG: 9
So I'm a bit lost to where this is going wrong. I think I have everything set up and going good. Like the inputstream, bufferreader and all. So here is what I have.
This is the Parser program
public class JSONParser extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... inputUrl) {
getStream(inputUrl[0]);
return null;
}
public void getStream(String urlString)
{
Log.d("HTML inJSON: ", urlString );
//variables for the connection and downloading the JSON data
URL url = null;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
Log.d("Status:","Connection Opened");
//read in the data
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
//build the data for parsing
StringBuilder myString = new StringBuilder();
String line;
while((line = br.readLine()) !=null)
{
myString.append(line);
}
Log.d("Status:"," JSON loaded into string");
Log.d("Total:", myString.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (urlConnection != null)
{
//close the connection
urlConnection.disconnect();
Log.d("Status:", " Closing connection");
}
}
}
}
And here is the main program I just run the thing because I just want to output from the file to the console I just want to make sure it works.
public class MainActivity extends AppCompatActivity {
//http://textfiles.com/100/914bbs.txt
private String testHtml = "http://textfiles.com/100/914bbs.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("HTML P1: ", testHtml );
JSONParser jp = new JSONParser();
Log.d("HTML P2: ", testHtml );
jp.getStream(testHtml);
Log.d("HTML P3: ", testHtml);
}
instead of using
jp.getStream(testHtml);
use
jp.execute("stream url here");
Currently you are trying to create a function in your Asynctask, but are not leveraging the use of AsyncTask. It still tries to make a HttpConnection on the mainThread, and that throws the exception.
I am trying to do an XMPP Connection with Smack 4.1.0 rc1 from https://github.com/igniterealtime/Smack
I followed this guide: https://github.com/igniterealtime/Smack/wiki/Smack-4.1-Readme-and-Upgrade-Guide importing the Gradle.
Source code:
package com.example.xmpp_app;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the configuration for this new connection
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword("test#example.com", "password123");
configBuilder.setResource("test");
configBuilder.setServiceName("example.com");
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
// Connect to the server
try {
connection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
// Log into the server
try {
connection.login();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Disconnect from the server
connection.disconnect();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
maven {
url 'https://oss.sonatype.org/content/repositories/snapshots'
}
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
build gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.example.xmpp_app"
minSdkVersion 15
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile "org.igniterealtime.smack:smack-java7:4.1.0-rc1"
// Optional for XMPPTCPConnection
compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
// Optional for XMPP-IM (RFC 6121) support (Roster, Threaded Chats, …)
compile "org.igniterealtime.smack:smack-im:4.1.0-rc1"
// Optional for XMPP extensions support
compile "org.igniterealtime.smack:smack-extensions:4.1.0-rc1"
}
ERROR:
03-20 20:34:33.830 1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
03-20 20:34:33.830 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 11345: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
03-20 20:34:33.850 1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
03-20 20:34:33.850 1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
03-20 20:34:33.850 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 11351: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
03-20 20:34:33.850 1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
03-20 20:34:33.920 1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
03-20 20:34:33.920 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 9039: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
03-20 20:34:33.950 1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
03-20 20:34:34.100 1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
03-20 20:34:34.110 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 364: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
03-20 20:34:34.110 1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
03-20 20:34:34.150 1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
03-20 20:34:34.150 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve virtual method 386: Landroid/content/res/TypedArray;.getType (I)I
03-20 20:34:34.150 1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
03-20 20:34:35.790 1005-1005/com.example.xmpp_app D/dalvikvm﹕ GC_FOR_ALLOC freed 221K, 9% free 3164K/3452K, paused 105ms, total 115ms
03-20 20:34:38.420 1005-1005/com.example.xmpp_app D/dalvikvm﹕ GC_FOR_ALLOC freed 295K, 10% free 3382K/3744K, paused 90ms, total 93ms
03-20 20:34:40.250 1005-1005/com.example.xmpp_app D/dalvikvm﹕ GC_FOR_ALLOC freed 349K, 11% free 3531K/3952K, paused 80ms, total 85ms
03-20 20:34:40.310 1005-1005/com.example.xmpp_app E/dalvikvm﹕ Could not find class 'javax.naming.directory.InitialDirContext', referenced from method org.jivesoftware.smack.util.dns.javax.JavaxResolver.<clinit>
03-20 20:34:40.310 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve new-instance 1688 (Ljavax/naming/directory/InitialDirContext;) in Lorg/jivesoftware/smack/util/dns/javax/JavaxResolver;
03-20 20:34:40.320 1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x22 at 0x000c
03-20 20:34:40.360 1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method javax.naming.directory.DirContext.getAttributes, referenced from method org.jivesoftware.smack.util.dns.javax.JavaxResolver.lookupSRVRecords
03-20 20:34:40.360 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve interface method 12701: Ljavax/naming/directory/DirContext;.getAttributes (Ljava/lang/String;[Ljava/lang/String;)Ljavax/naming/directory/Attributes;
03-20 20:34:40.370 1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0011
03-20 20:34:40.370 1005-1005/com.example.xmpp_app D/dalvikvm﹕ DexOpt: unable to opt direct call 0x319e at 0x0e in Lorg/jivesoftware/smack/util/dns/javax/JavaxResolver;.<clinit>
03-20 20:34:40.410 1005-1005/com.example.xmpp_app W/dalvikvm﹕ Exception Ljava/lang/NoClassDefFoundError; thrown while initializing Lorg/jivesoftware/smack/util/dns/javax/JavaxResolver;
03-20 20:34:41.330 1005-1005/com.example.xmpp_app I/dalvikvm﹕ Could not find method javax.security.sasl.Sasl.createSaslClient, referenced from method org.jivesoftware.smack.sasl.javax.SASLJavaXMechanism.authenticateInternal
03-20 20:34:41.330 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve static method 12731: Ljavax/security/sasl/Sasl;.createSaslClient ([Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Ljavax/security/auth/callback/CallbackHandler;)Ljavax/security/sasl/SaslClient;
03-20 20:34:41.340 1005-1005/com.example.xmpp_app D/dalvikvm﹕ VFY: replacing opcode 0x77 at 0x001a
03-20 20:34:41.340 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to resolve exception class 1708 (Ljavax/security/sasl/SaslException;)
03-20 20:34:41.350 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: unable to find exception handler at addr 0x21
03-20 20:34:41.350 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: rejected Lorg/jivesoftware/smack/sasl/javax/SASLJavaXMechanism;.authenticateInternal ()V
03-20 20:34:41.350 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: rejecting opcode 0x0d at 0x0021
03-20 20:34:41.350 1005-1005/com.example.xmpp_app W/dalvikvm﹕ VFY: rejected Lorg/jivesoftware/smack/sasl/javax/SASLJavaXMechanism;.authenticateInternal ()V
03-20 20:34:41.350 1005-1005/com.example.xmpp_app W/dalvikvm﹕ Verifier rejected class Lorg/jivesoftware/smack/sasl/javax/SASLJavaXMechanism;
03-20 20:34:41.370 1005-1005/com.example.xmpp_app W/dalvikvm﹕ Exception Ljava/lang/VerifyError; thrown while initializing Lorg/jivesoftware/smack/SmackInitialization;
03-20 20:34:41.370 1005-1005/com.example.xmpp_app W/dalvikvm﹕ Exception Ljava/lang/VerifyError; thrown while initializing Lorg/jivesoftware/smack/ConnectionConfiguration;
03-20 20:34:41.380 1005-1005/com.example.xmpp_app D/AndroidRuntime﹕ Shutting down VM
03-20 20:34:41.380 1005-1005/com.example.xmpp_app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a3bba8)
03-20 20:34:41.540 1005-1005/com.example.xmpp_app D/dalvikvm﹕ GC_FOR_ALLOC freed 438K, 14% free 3576K/4112K, paused 59ms, total 64ms
03-20 20:34:41.580 1005-1005/com.example.xmpp_app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.xmpp_app, PID: 1005
java.lang.VerifyError: org/jivesoftware/smack/sasl/javax/SASLJavaXMechanism
at org.jivesoftware.smack.sasl.javax.SASLJavaXSmackInitializer.initialize(SASLJavaXSmackInitializer.java:28)
at org.jivesoftware.smack.SmackInitialization.loadSmackClass(SmackInitialization.java:232)
at org.jivesoftware.smack.SmackInitialization.parseClassesToLoad(SmackInitialization.java:193)
at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:163)
at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:148)
at org.jivesoftware.smack.SmackInitialization.<clinit>(SmackInitialization.java:116)
at org.jivesoftware.smack.SmackConfiguration.getVersion(SmackConfiguration.java:96)
at org.jivesoftware.smack.ConnectionConfiguration.<clinit>(ConnectionConfiguration.java:38)
at com.example.xmpp_app.MainActivity.onCreate(MainActivity.java:29)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
03-20 20:39:44.485 1005-1005/com.example.xmpp_app I/Process﹕ Sending signal. PID: 1005 SIG: 9
Could someone help me with this problem, please? I am just trying to check if the connection works..
Replace smack-java7 with smack-android in your build.gradle. This is documented in Smack's README.
This is an upgrade of my last FCM XMPP Connection Server application. Now, this project uses the latest version at this time of the Smack library (4.1.8). I think that the library for android is pretty the same for the java server.
https://github.com/carlosCharz/fcmxmppserverv2
This is my sample java project to showcase the Firebase Cloud Messaging (FCM) XMPP Connection Server. This server sends data to a client app via the FCM CCS Server using the XMPP protocol.
https://github.com/carlosCharz/fcmxmppserver
And also I've created a video in youtube where I explain what the changes are.
https://www.youtube.com/watch?v=KVKEj6PeLTc
Hope you find it useful.
Here is a code snippet for the implementation:
public class CcsClient implements StanzaListener {
//Other code
public void connect() throws XMPPException, SmackException, IOException {
XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setServiceName("FCM XMPP Client Connection Server");
config.setHost(Util.FCM_SERVER);
config.setPort(Util.FCM_PORT);
config.setSecurityMode(SecurityMode.ifpossible);
config.setSendPresence(false);
config.setSocketFactory(SSLSocketFactory.getDefault());
// Launch a window with info about packets sent and received
config.setDebuggerEnabled(mDebuggable);
// Create the connection
connection = new XMPPTCPConnection(config.build());
// Connect
connection.connect();
// Enable automatic reconnection
ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection();
// Handle reconnection and connection errors
connection.addConnectionListener(new ConnectionListener() {
#Override
public void reconnectionSuccessful() {
logger.log(Level.INFO, "Reconnection successful ...");
// TODO: handle the reconnecting successful
}
#Override
public void reconnectionFailed(Exception e) {
logger.log(Level.INFO, "Reconnection failed: ",
e.getMessage());
// TODO: handle the reconnection failed
}
#Override
public void reconnectingIn(int seconds) {
logger.log(Level.INFO, "Reconnecting in %d secs", seconds);
// TODO: handle the reconnecting in
}
#Override
public void connectionClosedOnError(Exception e) {
logger.log(Level.INFO, "Connection closed on error");
// TODO: handle the connection closed on error
}
#Override
public void connectionClosed() {
logger.log(Level.INFO, "Connection closed");
// TODO: handle the connection closed
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
logger.log(Level.INFO, "User authenticated");
// TODO: handle the authentication
}
#Override
public void connected(XMPPConnection arg0) {
logger.log(Level.INFO, "Connection established");
// TODO: handle the connection
}
});
// Handle incoming packets (the class implements the StanzaListener)
connection.addAsyncStanzaListener(this,
stanza -> stanza.hasExtension(Util.FCM_ELEMENT_NAME, Util.FCM_NAMESPACE));
// Log all outgoing packets
connection.addPacketInterceptor(stanza -> logger.log(Level.INFO,
"Sent: {}", stanza.toXML()), stanza -> true);
connection.login(fcmServerUsername, mApiKey);
logger.log(Level.INFO, "Logged in: " + fcmServerUsername);
}
}
Try to connect server with XMPPConnection class.
How to connect:
XMPPConnection con = new XMPPTCPConnection("igniterealtime.org");
con.connect();
I'm trying to create a google glass application that uses the CamFind api to recognize objects from the camera. I've gotten maven to install, but it won't assemble the "master jar", so I'm adding dependencies to the gradle build path. I've gotten it to compile without any errors (granted there are 8 warnings), but it won't complete the call to the api without erroring out.
Here's the relevant code:
package com.akqa.glass.recipie;
import android.util.Log;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
// For if I'm using Unirest - don't it's not working...
//import org.apache.http.HttpResponse;
//import org.shaded.apache.http.HttpHeaders;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
private static final String TAG = JSONParser.class.getSimpleName();
// constructor
public JSONParser() {
}
public JSONObject getCamFindJSON(String type, String input) {
Log.d("PARSER", "Inside Parser");
/*
* Request processing from API
*/
if(type == "request"){
try {
HttpResponse<JsonNode> response = Unirest.post("https://camfind.p.mashape.com/image_requests")
.header("X-Mashape-Key", "Fhn5jZi5ixmshwnJMy7CGyj5yDCnp15DTQZjsniuwpVHfYHvFJ")
.field("image_request[image]", new File(input))
.field("image_request[locale]", "en_US")
.asJson();
} catch (UnirestException e) {
e.printStackTrace();
}
}
/*
* Receive response from API
*/
else if(type == "response"){
// These code snippets use an open-source library. http://unirest.io/java
try {
HttpResponse<JsonNode> response = Unirest.get("https://camfind.p.mashape.com/image_responses/" + input)
.header("X-Mashape-Key", "Fhn5jZi5ixmshwnJMy7CGyj5yDCnp15DTQZjsniuwpVHfYHvFJ")
.asJson();
} catch (UnirestException e) {
e.printStackTrace();
}
}
/*
* Parse Response into readable JSON
*/
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
Log.d("Raw Data", line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e("JSON Parse", "Unknown Error");
e.printStackTrace();
}
// return JSON String
return jObj;
}
}
And here's the relevant gradle build path:
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile files('C:/Users/torti_000/Documents/Recip.ie/libs/unirest-java-1.3.26.jar')
compile 'org.apache.httpcomponents:httpclient:4.3.5'
// compile 'org.apache.httpcomponents:httpclient-android:4.3.3'
compile 'org.apache.httpcomponents:httpmime:4.3.5'
compile 'org.apache.httpcomponents:httpasyncclient:4.0.2'
}
Finally, here's the logcat output (I'm pretty sure it's the first line that's causing all the problems):
11-25 14:21:59.589 6847-7099/com.akqa.glass.recipie E/dalvikvm﹕ Could not find class 'org.apache.http.impl.client.CloseableHttpClient', referenced from method com.mashape.unirest.http.Unirest.shutdown
11-25 14:21:59.589 6847-7099/com.akqa.glass.recipie W/dalvikvm﹕ VFY: unable to resolve check-cast 451 (Lorg/apache/http/impl/client/CloseableHttpClient;) in Lcom/mashape/unirest/http/Unirest;
11-25 14:21:59.589 6847-7099/com.akqa.glass.recipie D/dalvikvm﹕ VFY: replacing opcode 0x1f at 0x0006
11-25 14:21:59.605 6847-7099/com.akqa.glass.recipie I/dalvikvm﹕ Could not find method org.apache.http.client.methods.HttpRequestBase.releaseConnection, referenced from method com.mashape.unirest.http.HttpClientHelper.request
11-25 14:21:59.605 6847-7099/com.akqa.glass.recipie W/dalvikvm﹕ VFY: unable to resolve virtual method 1095: Lorg/apache/http/client/methods/HttpRequestBase;.releaseConnection ()V
11-25 14:21:59.605 6847-7099/com.akqa.glass.recipie D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0012
11-25 14:21:59.605 6847-7099/com.akqa.glass.recipie I/dalvikvm﹕ Could not find method org.apache.http.client.methods.HttpRequestBase.releaseConnection, referenced from method com.mashape.unirest.http.HttpClientHelper.request
11-25 14:21:59.605 6847-7099/com.akqa.glass.recipie W/dalvikvm﹕ VFY: unable to resolve virtual method 1095: Lorg/apache/http/client/methods/HttpRequestBase;.releaseConnection ()V
11-25 14:21:59.605 6847-7099/com.akqa.glass.recipie D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0021
11-25 14:21:59.613 6847-7099/com.akqa.glass.recipie I/dalvikvm﹕ Could not find method org.apache.http.client.config.RequestConfig.custom, referenced from method com.mashape.unirest.http.options.Options.refresh
11-25 14:21:59.613 6847-7099/com.akqa.glass.recipie W/dalvikvm﹕ VFY: unable to resolve static method 1069: Lorg/apache/http/client/config/RequestConfig;.custom ()Lorg/apache/http/client/config/RequestConfig$Builder;
11-25 14:21:59.613 6847-7099/com.akqa.glass.recipie D/dalvikvm﹕ VFY: replacing opcode 0x71 at 0x0020
11-25 14:21:59.613 6847-7099/com.akqa.glass.recipie D/dalvikvm﹕ DexOpt: unable to opt direct call 0x070c at 0x49 in Lcom/mashape/unirest/http/options/Options;.refresh
11-25 14:21:59.613 6847-7099/com.akqa.glass.recipie W/dalvikvm﹕ Exception Ljava/lang/NoClassDefFoundError; thrown while initializing Lcom/mashape/unirest/http/options/Options;
11-25 14:21:59.620 6847-7099/com.akqa.glass.recipie W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4162bbd8)
11-25 14:21:59.620 6847-7101/com.akqa.glass.recipie D/PARSER﹕ Inside Parser
11-25 14:21:59.620 6847-7101/com.akqa.glass.recipie I/dalvikvm﹕ Rejecting re-init on previously-failed class Lcom/mashape/unirest/http/options/Options; v=0x0
11-25 14:21:59.620 6847-7099/com.akqa.glass.recipie E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.akqa.glass.recipie, PID: 6847
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:314)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:240)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.client.config.RequestConfig
at com.mashape.unirest.http.options.Options.refresh(Options.java:45)
at com.mashape.unirest.http.options.Options.<clinit>(Options.java:34)
at com.mashape.unirest.http.HttpClientHelper.prepareRequest(HttpClientHelper.java:153)
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:133)
at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
at com.akqa.glass.recipie.JSONParser.getCamFindJSON(JSONParser.java:42)
at com.akqa.glass.recipie.RecipIE$CamFindRequest.doInBackground(RecipIE.java:288)
at com.akqa.glass.recipie.RecipIE$CamFindRequest.doInBackground(RecipIE.java:275)
at android.os.AsyncTask$2.call(AsyncTask.java:302)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:240)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
11-25 14:21:59.628 6847-7101/com.akqa.glass.recipie W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0x4162bbd8)
11-25 14:21:59.628 6847-7101/com.akqa.glass.recipie I/Process﹕ Sending signal. PID: 6847 SIG: 9
The way to solve this is to compile all the dependencies into the mega jar as stated in the instructions. I couldn't do that, so I am using retrofit instead. I'll later update this with a link to a blog post about how to use retrofit with Mashape APIs.