How to count data in Java - java

I try count data and remove Duplicate data by the following code ,but I got an error message with this code.
Can anyone help me?
StructorRecords.java
public class StructorRecords {
public String recorusername;
public String id;
public String full_name;
public String recordimg;
public Integer count;}
counter.java
public static void orderbylike(StructorRecords data) {
if (G.bollike) {
G.savelike.add(data);
} else {
Iterator itr = G.savelike.iterator();
int i = 1;
while (itr.hasNext()) {
StructorRecords SR = (StructorRecords) itr.next();
if (SR.id.equals(data.id)) {
data.count = SR.count + 1;
G.savelike.set(i, data);
} else {
G.savelike.add(data);
}
i++;
}
}
}
this is logs that get me
LOG
02-01 17:19:23.142 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: java.util.ConcurrentModificationException
02-01 17:19:23.152 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
02-01 17:19:23.152 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.counter.orderbylike(counter.java:21)
02-01 17:19:23.152 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.loginActivity$11.run(loginActivity.java:460)
02-01 17:19:23.162 7587-9416/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.lang.Thread.run(Thread.java:856)
02-01 17:19:23.451 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: java.util.ConcurrentModificationException
02-01 17:19:23.451 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
02-01 17:19:23.451 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.counter.orderbylike(counter.java:21)
02-01 17:19:23.461 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.loginActivity$11.run(loginActivity.java:460)
02-01 17:19:23.461 7587-9472/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.lang.Thread.run(Thread.java:856)
02-01 17:19:23.583 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: java.util.ConcurrentModificationException
02-01 17:19:23.583 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
02-01 17:19:23.583 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.counter.orderbylike(counter.java:21)
02-01 17:19:23.583 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at sanjinsgr.limosoftwaregroup.ir.instasanj.loginActivity$11.run(loginActivity.java:460)
02-01 17:19:23.592 7587-9417/sanjinsgr.limosoftwaregroup.ir.instasanj W/System.err: at java.lang.Thread.run(Thread.java:856)

Error is there because
you try to add element to the List (I assume G.savelike is a List), while you iterate through the same list with iterator.
It is not allowed. Instead make another tmpList for all new elements, add them in it and after iterator loop done use addAll() method.
Like that:
List<StructorRecords> tmpList = new ArrayList<StructorRecords> tmpList;
while (itr.hasNext()) {
StructorRecords SR = (StructorRecords) itr.next();
if (SR.id.equals(data.id)) {
data.count = SR.count + 1;
G.savelike.set(i, data);
} else {
// here put to temp list
tmpList.add(data);
}
i++;
}
// add all new elements
G.savelike.addAll(tmpList);

You can use the Collections from java concurrency package which will provide fail safe iterator, If you use Collections from java.util package the iterators are of Fail fast type and will throw Concurrent modification exception whenever you iterate and try update the collection at the same time.

Related

Added mysql-connector, but connection is still dying

I try to send query to my database in android studio, i managed this a few years back with eclipse, but now i want to code apps with this IDE
First i show you my code:
private static int getAktuelleArtikelID() throws NumberFormatException, SQLException
{
ResultSet ergebnisSet = null;
int ergebnis;
try
{
Connection verbindung = DriverManager.getConnection("jdbc:mysql://localhost:3306/foo", "bar", "foobar!");
Statement statement = verbindung.createStatement();
String abfrage = "SELECT artikel_id FROM Artikel order by 1 desc limit 1";
ergebnisSet = statement.executeQuery(abfrage);
ergebnisSet.next();
}
catch (Exception exc)
{
exc.printStackTrace();
}
ergebnis = Integer.parseInt(ergebnisSet.getString(1));
return ergebnis;
}
The Code seems right in my opinoin, i rather have the problem with jdbc.
I added the mysqlconnector 5.1.44 like eplained here:
Answer 2 from
How to Mysql JDBC Driver to android studio
But i get this error:
W/System.err: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
W/System.err: at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err: at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err: at com.mysql.jdbc.Util.getInstance(Util.java:408)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err: at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2268)
W/System.err: at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2017)
W/System.err: at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
W/System.err: at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
W/System.err: at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err: at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err: at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
W/System.err: at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:569)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err: at com.example.androidcameraapi2.Database.getAktuelleArtikelID(Database.java:20)
W/System.err: at com.example.androidcameraapi2.Database.artikelHochladen(Database.java:40)
W/System.err: at com.example.androidcameraapi2.MainActivity$7.onClick(MainActivity.java:227)
W/System.err: at android.view.View.performClick(View.java:6597)
W/System.err: at android.view.View.performClickInternal(View.java:6574)
W/System.err: at android.view.View.access$3100(View.java:778)
W/System.err: at android.view.View$PerformClick.run(View.java:25885)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:193)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6669)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
W/System.err: at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
at java.net.InetAddress.getAllByName(InetAddress.java:1154)
W/System.err: at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
W/System.err: at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189)
W/System.err: at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2222)
W/System.err: ... 24 more
D/AndroidRuntime: Shutting down VM
Also graddle wants an update, but i already tried it and it seems to make everything worse
Here are some suggestions:
Never, ever pass a ResultSet out of method scope. You create it in a method and clean it up in that method. Load the data into objects and return those to the caller.
Never, ever create a Connection in a data access class this way. You should be using pooled connections.
Real applications log exceptions.
Stick to SQL that isn't database specific (e.g. MySQL). You keep your code portable that way.
If a value should be unique, build that requirement into your schema, not the query that fetches it.
Connection parameters like URL, username, password should be externalized from your app in configuration.
You should never use a database admin credential in an application.
Plain text credentials are an invitation to break into your database.
Here's how I might write your method:
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* JDBC demo.
* User: mduffy
* Date: 5/8/19
* Time: 2:37 PM
* #link https://stackoverflow.com/questions/56046854/added-mysql-connector-but-connection-is-still-dying?noredirect=1#comment98735575_56046854
*/
public class JdbcDemo {
private static final String SELECT_SQL = "SELECT artikel_id FROM Artikel ";
private DataSource dataSource;
public JdbcDemo(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<String> getAktuelleArtikelID() {
List<String> aktuelleArtikelId = new ArrayList<>();
ResultSet rs = null;
Statement st = null;
try {
st = this.dataSource.getConnection().createStatement();
rs = st.executeQuery(SELECT_SQL);
while (rs.next()) {
aktuelleArtikelId.add(rs.getString(1));
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
close(rs);
close(st);
}
return aktuelleArtikelId;
}
// Should be in a utility class
private static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void close(Statement st) {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Getting `File not found` errors for an `asset`. How can this be?

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

Unable to resolve host "My URL" - No address associated with hostname

The exception occurs randomly and then its hard to get rid of. I am tired of this error and despite the fact that I have tried almost everything on stackoverflow from changing url to respective IP address, using real device, adding internet permissions as mentioned or checking wifi connection. Everything is all right except the error which keeps coming back. Yes I also added checking connection code as below :
try {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
URL url = new URL(urlx);
HttpURLConnection urlc = (HttpURLConnection) url
.openConnection();
urlc.setConnectTimeout(1000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
upsuccess = true;
}
});
} else {
runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
upsuccess = false;
}
});
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and System.setProperty("http.proxyHost", "myurl.com");
System.setProperty("http.proxyPort", "8080");
but each of them separately as well as together did not fetch me any useful results. Can you suggest me what to do?
I am basically doing this : I am uploading a pdf file on my server and loading the google docs viewer url with that url. I however see the following exception several times. I also added retrying in case I find the exception but the exception randomly happens and is not easy to get out of if you encounter it.
Exception :
java.net.UnknownHostException: Unable to resolve host "myurl.com": No
address associated with hostname 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:95)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at java.net.InetAddress.getAllByName(InetAddress.java:752) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.Dns$1.lookup(Dns.java:39) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:172)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.getResponse(RealCall.java:243) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.execute(RealCall.java:57) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
securitymsg.listmydocs.CloudViewer$UploadFileAsync.doInBackground(CloudViewer.java:678)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
securitymsg.listmydocs.CloudViewer$UploadFileAsync.doInBackground(CloudViewer.java:650)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at android.os.AsyncTask$2.call(AsyncTask.java:305) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
java.util.concurrent.FutureTask.run(FutureTask.java:237) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at java.lang.Thread.run(Thread.java:761) 07-20 01:12:13.016
24907-24907/securitymsg.listmydocs W/cr_BindingManager: Cannot call
determinedVisibility() - never saw a connection for the pid: 24907
07-20 01:12:13.677 24907-24907/securitymsg.listmydocs
W/cr_BindingManager: Cannot call determinedVisibility() - never saw a
connection for the pid: 24907 07-20 01:12:13.678
24907-24907/securitymsg.listmydocs W/cr_BindingManager: Cannot call
determinedVisibility() - never saw a connection for the pid: 24907
My Permissions in manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
My code to upload file :
*PHP :
<?php
$file_path = "images/";
$neran = $_GET['neran'];
$ext = pathinfo(basename( $_FILES['uploaded_file']['name']), PATHINFO_EXTENSION);
$file_path = "images/".$neran.".".$ext;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
echo "success";
} else{
echo "fail";
}
?>
Android side (I use Retrofit) : The following code is in doinbackground block of AsyncTask
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
Log.e("msh", content_type);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("http://reviewitapp.co/retrofit_example/save_file.php?neran="+neran)
.post(request_body)
.build();
response = client.newCall(request).execute();
} catch (UnknownHostException e) {
e.printStackTrace();
/*uploadFile(selectedFilePath);*/
upsuccess = false;
} catch (IOException e) {
e.printStackTrace();
upsuccess = false;
} catch (NullPointerException e) {
e.printStackTrace();
/*uploadFile(selectedFilePath);*/
upsuccess = false;
}
if(response!=null) {
if (response.isSuccessful()) {
upsuccess = true;
}
response.body().close();
}

Android Dropbox API v1 upload file and get shared link of this file

I have uploaded file and when I try to get the shared link then it gives NullPointerException.
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + mFile.getName();
DropboxAPI.Entry response = mApi.putFile(path, fis,
mFile.length(), null, new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
if (response != null) {
mErrorMsg=response.path;
Log.e("DbExampleLog", "*****"+response.path+" The uploaded file's rev is: " + response.rev);
DropboxAPI.DropboxLink shareLink = mApi.share(response.path);
Log.e("DbExampleLog", "*****"+shareLink+" The uploaded file's rev is: " + response.rev);
if(shareLink!=null) {
if(shareLink.url!=null) {
Log.e("Null error URL*****",""+shareLink.url);
Log.e("Null error URL*****",""+getShareURL(shareLink.url));
String shareAddress = getShareURL(shareLink.url).toString();
Log.e("DbExampleLog", "URL -" + shareAddress + "*****" + response.path + " The uploaded file's rev is: " + response.rev);
}
else
Log.e("Null error URL*****",""+shareLink.url);
}
else{
Log.e("Null error*****",""+shareLink);
}
return true;
}
It returns like -
12-05 12:09:09.207 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/DbExampleLog: *****/1480919937073.jpg The uploaded file's rev is: 2ef4a7ca38e
12-05 12:09:10.966 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/DbExampleLog: *****com.dropbox.client2.DropboxAPI$DropboxLink#d9d5da1 The uploaded file's rev is: 2ef4a7ca38e
12-05 12:09:10.966 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/Null error URL*****: https://db.tt/ru6e39XK0
12-05 12:09:12.457 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/Null error URL*****: null
12-05 12:09:13.520 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.trucker.gtd.satyaki.dropboxintegrationapiv1, PID: 7335
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.doInBackground(UploadFile.java:147)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.doInBackground(UploadFile.java:63)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
12-05 12:09:13.645 1248-1248/? E/EGL_emulation: tid 1248: eglCreateSyncKHR(1641): error 0x3004 (EGL_BAD_ATTRIBUTE)
12-05 12:09:13.796 2071-2205/com.android.launcher3 E/EGL_emulation: tid 2205: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
12-05 12:09:14.006 1530-1640/system_process E/EGL_emulation: tid 1640: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
12-05 12:09:14.304 7335-7335/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/WindowManager: android.view.WindowLeaked: Activity com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main has leaked window DecorView#3bf9cac[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at com.dropbox.client2.android.AuthActivity.checkAppBeforeAuth(AuthActivity.java:284)
at com.dropbox.client2.android.AndroidAuthSession.startAuthentication(AndroidAuthSession.java:213)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.onActivityResult(Main.java:132)
at android.app.Activity.dispatchActivityResult(Activity.java:6915)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
12-05 12:09:14.310 7335-7335/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/WindowManager: android.view.WindowLeaked: Activity com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main has leaked window DecorView#e8ad10a[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.<init>(UploadFile.java:98)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.setLoggedIn(Main.java:144)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.onResume(Main.java:168)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6766)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3377)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1510)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Mainly in this particular line-
getShareURL(shareLink.url)
Please suggest me why this error occur, but yesterday using this code it worked.
UPDATE CODE ASKED BY Greg
String getShareURL(String strURL) {
URLConnection conn = null;
String redirectedUrl = null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
System.out.println("Redirected URL: " + conn.getURL());
Log.e("Get Redirected URL",""+conn.getURL());
redirectedUrl = conn.getURL().toString();
is.close();
} catch (MalformedURLException e) {
Log.e("TAG", "Please input a valid URL");
} catch (IOException ioe) {
Log.e("TAG", "Can not connect to the URL");
}
return redirectedUrl;
}
This code taken from Share file in Dropbox

Saving an array for data persistence gets a null pointer exception with gson

I am not going to post ALL the code, because there is hundreds of lines, but I will post the lines that are returned with my null pointer exception in LOGCAT, as well as the LOADFROMFILE And SAVETOFILE methods I use for the Gson serialization and data storage.
First error points here:
Gson gson = new Gson();
try {
FileOutputStream fos = openFileOutput(SAVEFILE,0); // This line is the error
OutputStreamWriter osw = new OutputStreamWriter(fos);
Second point:
AddClaim cla = new AddClaim();
cla.saveInFile(claim); // This line is the error
Third point:
public void addClaim(Claim claim){
getClaimList().addClaim(claim);
Fourth point:
this.edate = getDateFromDatePicket(edatePicker);
addClaims(v);
Fifth/final point:
public void addClaims(View v){
ClaimListController ct = new ClaimListController();
Claim addClaim = new Claim(name, sdate, edate);
ct.addClaim(addClaim);
Toast.makeText(this,"Added "+name, Toast.LENGTH_SHORT).show();
}
Now it seems to me these errors all have in common that I am trying to add a new claim. HOWEVER, when I remove the file persistence code and just run it with no storage, the code works and the claims show on my app. This must mean that it is not the claims that are coming through as null but something else? What is that something else?
Oh, and here are the two methods in Add Claim I use to Save and Load the data from file:
As an attribute of the class I have:
String SAVEFILE = "file.sav";
Then the rest of the code and then the two methods for loading and saving:
public void saveInFile(Claim claim) {
Gson gson = new Gson();
try {
FileOutputStream fos = openFileOutput(SAVEFILE,0);
OutputStreamWriter osw = new OutputStreamWriter(fos);
gson.toJson(claim, osw);
osw.flush();
fos.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Recover those persistent data created in the save function
private ArrayList<Claim> loadFromFile() {
Gson gson = new Gson();
ArrayList<Claim> claim = new ArrayList<Claim>();
try {
FileInputStream fis = openFileInput(SAVEFILE);
//Based on http://google.gson.googlecode.com/svn/trunk/gson/dos/javadoc/com/google/gson/Gson.html
Type listType = new TypeToken<ArrayList<Claim>>(){}.getType();
InputStreamReader isr = new InputStreamReader(fis);
claim = gson.fromJson(isr, listType);
fis.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (claim == null){
claim = new ArrayList<Claim>();
}
return claim;
}
Please let me know what else I need.
Here is the LOGCAT
02-01 01:05:37.105: E/AndroidRuntime(23093): FATAL EXCEPTION: main
02-01 01:05:37.105: E/AndroidRuntime(23093): Process: app.zioueche_travelexpense, PID: 23093
02-01 01:05:37.105: E/AndroidRuntime(23093): java.lang.IllegalStateException: Could not execute method of the activity
02-01 01:05:37.105: E/AndroidRuntime(23093): at android.view.View$1.onClick(View.java:3969)
02-01 01:05:37.105: E/AndroidRuntime(23093): at android.view.View.performClick(View.java:4633)
02-01 01:05:37.105: E/AndroidRuntime(23093): at android.view.View$PerformClick.run(View.java:19330)
02-01 01:05:37.105: E/AndroidRuntime(23093): at android.os.Handler.handleCallback(Handler.java:733)
02-01 01:05:37.105: E/AndroidRuntime(23093): at android.os.Handler.dispatchMessage(Handler.java:95)
02-01 01:05:37.105: E/AndroidRuntime(23093): at android.os.Looper.loop(Looper.java:157)
02-01 01:05:37.105: E/AndroidRuntime(23093): at android.app.ActivityThread.main(ActivityThread.java:5356)
02-01 01:05:37.105: E/AndroidRuntime(23093): at java.lang.reflect.Method.invokeNative(Native Method)
02-01 01:05:37.105: E/AndroidRuntime(23093): at java.lang.reflect.Method.invoke(Method.java:515)
02-01 01:05:37.105: E/AndroidRuntime(23093): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
02-01 01:05:37.105: E/AndroidRuntime(23093): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
02-01 01:05:37.105: E/AndroidRuntime(23093): at dalvik.system.NativeStart.main(Native Method)
02-01 01:05:37.105: E/AndroidRuntime(23093): Caused by: java.lang.reflect.InvocationTargetException
02-01 01:05:37.105: E/AndroidRuntime(23093): at java.lang.reflect.Method.invokeNative(Native Method)
02-01 01:05:37.105: E/AndroidRuntime(23093): at java.lang.reflect.Method.invoke(Method.java:515)
02-01 01:05:37.105: E/AndroidRuntime(23093): at android.view.View$1.onClick(View.java:3964)
02-01 01:05:37.105: E/AndroidRuntime(23093): ... 11 more
02-01 01:05:37.105: E/AndroidRuntime(23093): Caused by: java.lang.NullPointerException
02-01 01:05:37.105: E/AndroidRuntime(23093): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:197)
02-01 01:05:37.105: E/AndroidRuntime(23093): at app.zioueche_travelexpense.AddClaim.saveInFile(AddClaim.java:244)
02-01 01:05:37.105: E/AndroidRuntime(23093): at app.zioueche_travelexpense.ClaimsList.addClaim(ClaimsList.java:37)
02-01 01:05:37.105: E/AndroidRuntime(23093): at app.zioueche_travelexpense.ClaimListController.addClaim(ClaimListController.java:19)
02-01 01:05:37.105: E/AndroidRuntime(23093): at app.zioueche_travelexpense.NewClaim.addClaims(NewClaim.java:34)
02-01 01:05:37.105: E/AndroidRuntime(23093): at app.zioueche_travelexpense.NewClaim.getEDate(NewClaim.java:68)
Line 244 starts with:
try {
FileOutputStream fos = openFileOutput(SAVEFILE,0);
OutputStreamWriter osw = new OutputStreamWriter(fos);
gson.toJson(claim, osw);
osw.flush();
fos.close();
}
In your loadFromFile() method add these four lines at the very top:
File myFile = new File(SAVEFILE);
System.out.println("Method 1, file exists?: " + myFile.exists());
File myFile2 = new File(getFilesDir(), "/" + SAVEFILE);
System.out.println("Method 2, file exists?: " + myFile2.exists());
If in both you get false then I don't know the answer.
If you get true at the second then you probably need to provide the absolute path when you look for your file.

Categories

Resources