['Http Connection'] App is crashing - Java for Android App Development

Hello guys,
Well, I was working with data sharing via http. So, I made an app in which the app downloads a image after a certain button is clicked. However the app is crashing at that moment.
But when I execute
Code:
new DownloadImageTask().execute(myUrl);
from OnCreate, the app just works fine. I am completely lost here. Please help me out!
I am giving you the MainActivity.class and the logcat.
Thanks
MainActivity.class
Code:
package com.example.neew;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener{
ImageView img;
TextView text;
Thread t;
Button b;
Handler handler=new Handler();
String myUrl="http://s27.postimg.org/epsajh82q/Nissan_Skyline_Wallpaper_Photos_HD.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img=(ImageView)findViewById(R.id.images);
text=(TextView)findViewById(R.id.tex);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private InputStream openHttpConnection(String urlString) throws IOException{
InputStream in=null;
int response=-1;
URL url=new URL(urlString);
URLConnection urlconnection=url.openConnection();
if(!(urlconnection instanceof HttpURLConnection )){
Toast.makeText(getBaseContext(),
"Not an Http protocol",
Toast.LENGTH_LONG).show();
}else{
try{
HttpURLConnection conn=(HttpURLConnection)urlconnection;
conn.setAllowUserInteraction(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("GET");
conn.connect();
text.setText("conn made");
response=conn.getResponseCode();
if(response==HttpURLConnection.HTTP_OK){
//text.setText("Connection made-Protocol accepted");
runner("Protocol is setuped");
in=conn.getInputStream();
}
}catch(Exception e){
Toast.makeText(getBaseContext(), e.toString(), 3000).show();
}
}
//text.setText("Stream returned");
runner("stream is returned");
return in;
}
private Bitmap downloadImage(String url){
Bitmap bitmap=null;
InputStream input=null;
try{
input=openHttpConnection(url);
bitmap=BitmapFactory.decodeStream(input);
input.close();
}catch(IOException e){
Toast.makeText(getApplicationContext(), e.toString(), 3467).show();
}
runner("Bitmap is downloaded");
return bitmap;
}
public void Theader(final String msg){
t=new Thread(new Runnable(){
public void run(){
handler.post(new Runnable(){
public void run(){
text.setText(msg);
}
});
}
});
t.start();
}
@SuppressWarnings("deprecation")
public void runner(String s){
Theader(s);
if(text.getText().toString()==s)
{
t.stop();
}
}
private class DownloadImageTask extends AsyncTask<String,Void,Bitmap>{
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
runner("Downloading bitmap");
return downloadImage(params[0]);
}
protected void onPostExecute(Bitmap result){
runner("Bitmap is set");
img.setImageBitmap(result);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DownloadImageTask().execute(myUrl);
}
}
________________________________________________________________________________________________
Logcat
Code:
08-16 09:12:22.442: I/dalvikvm(707): threadid=3: reacting to signal 3
08-16 09:12:22.518: I/dalvikvm(707): Wrote stack traces to '/data/anr/traces.txt'
08-16 09:12:22.962: I/dalvikvm(707): threadid=3: reacting to signal 3
08-16 09:12:23.022: I/dalvikvm(707): Wrote stack traces to '/data/anr/traces.txt'
08-16 09:12:23.481: I/dalvikvm(707): threadid=3: reacting to signal 3
08-16 09:12:23.511: I/dalvikvm(707): Wrote stack traces to '/data/anr/traces.txt'
08-16 09:12:23.631: D/gralloc_goldfish(707): Emulator without GPU emulation detected.
08-16 09:25:43.031: W/dalvikvm(707): threadid=11: thread exiting with uncaught exception (group=0x2ba041f8)
08-16 09:25:43.061: E/AndroidRuntime(707): FATAL EXCEPTION: AsyncTask #1
08-16 09:25:43.061: E/AndroidRuntime(707): java.lang.RuntimeException: An error occured while executing doInBackground()
08-16 09:25:43.061: E/AndroidRuntime(707): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-16 09:25:43.061: E/AndroidRuntime(707): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-16 09:25:43.061: E/AndroidRuntime(707): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-16 09:25:43.061: E/AndroidRuntime(707): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-16 09:25:43.061: E/AndroidRuntime(707): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-16 09:25:43.061: E/AndroidRuntime(707): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-16 09:25:43.061: E/AndroidRuntime(707): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-16 09:25:43.061: E/AndroidRuntime(707): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-16 09:25:43.061: E/AndroidRuntime(707): at java.lang.Thread.run(Thread.java:856)
08-16 09:25:43.061: E/AndroidRuntime(707): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-16 09:25:43.061: E/AndroidRuntime(707): at android.os.Handler.<init>(Handler.java:121)
08-16 09:25:43.061: E/AndroidRuntime(707): at android.widget.Toast$TN.<init>(Toast.java:317)
08-16 09:25:43.061: E/AndroidRuntime(707): at android.widget.Toast.<init>(Toast.java:91)
08-16 09:25:43.061: E/AndroidRuntime(707): at android.widget.Toast.makeText(Toast.java:233)
08-16 09:25:43.061: E/AndroidRuntime(707): at com.example.neew.MainActivity.openHttpConnection(MainActivity.java:86)
08-16 09:25:43.061: E/AndroidRuntime(707): at com.example.neew.MainActivity.downloadImage(MainActivity.java:97)
08-16 09:25:43.061: E/AndroidRuntime(707): at com.example.neew.MainActivity.access$0(MainActivity.java:93)
08-16 09:25:43.061: E/AndroidRuntime(707): at com.example.neew.MainActivity$DownloadImageTask.doInBackground(MainActivity.java:138)
08-16 09:25:43.061: E/AndroidRuntime(707): at com.example.neew.MainActivity$DownloadImageTask.doInBackground(MainActivity.java:1)
08-16 09:25:43.061: E/AndroidRuntime(707): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-16 09:25:43.061: E/AndroidRuntime(707): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-16 09:25:43.061: E/AndroidRuntime(707): ... 5 more
08-16 09:25:47.902: I/Process(707): Sending signal. PID: 707 SIG: 9

Wohooooo !!!is anybody there
Sent from my GT-P3100 using XDA Free mobile app

hiphop12ism said:
Wohooooo !!!is anybody there
Sent from my GT-P3100 using XDA Free mobile app
Click to expand...
Click to collapse
If you read the logcat it tells you the exact line in your code that is causing the error.
Sent from my HTC One using Tapatalk

Yes i have
Sent from my GT-P3100 using XDA Free mobile app

hiphop12ism said:
Yes i have
Click to expand...
Click to collapse
This is not the way I'd normally answer, but my advice is to use volley for all internet things. They even had an IO talk about it

Gohan said:
Is this for downloading or can it be used to send data to POST php scripts?
Click to expand...
Click to collapse
You should be able to use it for both, at some point you select if you want httpPost or get and if you want it to be a String or JSON or some other request.

Can't create handler inside thread that has not called Looper.prepare()
you should create a handler as a field, call its when you need, not create new hanlder in thread

But it is working perfectly fine when i execute asynctask from onCreate.
Ps: sorry I am quite new to multithreading
Sent from my GT-P3100 using XDA Free mobile app

Related

Getting a widget to pull data from database?

Right so I've created a very basic widget. It does nothing but display some text. The mechanics to setting it up are easy to learn. Now that I've learnt that I have to move on to what I actually want my widget to do. That would be where the database is involved. I want it to pull data from a database and have it show on my widget.
Eventually I will progress it so that the user can tap on it to bring up another bit of data from the database or just have a button do it. Right now though I just need to just get the data to show up. Let's say I have 500 rows, well I want the database to pull 1 row at random.
You don't need to tell me about the basics of a database because I already know that, I've used SQLite and all that, it's just getting it to work with a AppWidgetProvider that I can't get.
In fact I can already pull a random row from a database but I've only done it in an Activity. So how do I do this for a widget? Hopefully somoene here has experience with widgets!
I would really appreciate any help, thanks!
I used RemoteViews to manipulate/access my widget buttons from the provider. I'm not sure what type of view you are working with but look those up. It may be what you are looking for.
zalez said:
I used RemoteViews to manipulate/access my widget buttons from the provider. I'm not sure what type of view you are working with but look those up. It may be what you are looking for.
Click to expand...
Click to collapse
Interesting. I'll look into that. I saw some bits of code with RemoteViews but I have no idea about them so I better get learning.
Any chance there are some decent tutorials out there? I get the idea that a RemoteView is what handles the communication for the UI but I still don't get how I can pull data with that involved.
I mean would this work for example: http://stackoverflow.com/questions/5661815/app-with-widget-accesing-to-database?rq=1
I've seen some with tonnes of code and then there's the one above which only has a few lines.
When I went through this, I didn't find any tutorials so I pushed through it myself. Do you have a class to do your database queries?
Using a remote view to change the text you could use something like this inside your onUpdate:
Code:
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); //set your widget layout
remoteViews.setImageViewResource(R.id.btnToggle, R.drawable.toggle_off); //this changes the image in the imageview btnToggle, remoteViews lets you use setText and a couple of other to manipulate certain widget items
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
This is just a quick example pulled from one of my apps, you could put the database function above it to grab the line of text you want and then set the text in the remote view. The updateAppWidget will update all widgets with this view so if you have multitple different widgets then you'll need to pass the specific widgetId rather then the array.
If you want it to update with a button press on the widget, I would advice you set a pending intent which launches a service, does what you need it to do and then the service update the widget using remote views much like the above code.
Hope that helps
zalez said:
When I went through this, I didn't find any tutorials so I pushed through it myself. Do you have a class to do your database queries?
Click to expand...
Click to collapse
I am using the AppWidgetProvider to carry on my database query, within the onUpdate method. I have posted my code in the link below, on a question I asked on SO.
crazyfool_1 said:
Using a remote view to change the text you could use something like this inside your onUpdate:
Code:
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); //set your widget layout
remoteViews.setImageViewResource(R.id.btnToggle, R.drawable.toggle_off); //this changes the image in the imageview btnToggle, remoteViews lets you use setText and a couple of other to manipulate certain widget items
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
This is just a quick example pulled from one of my apps, you could put the database function above it to grab the line of text you want and then set the text in the remote view. The updateAppWidget will update all widgets with this view so if you have multitple different widgets then you'll need to pass the specific widgetId rather then the array.
If you want it to update with a button press on the widget, I would advice you set a pending intent which launches a service, does what you need it to do and then the service update the widget using remote views much like the above code.
Hope that helps
Click to expand...
Click to collapse
Since my last post I have actually done something similar to this, if not the exact same thing. I had to post a question to stack overflow because I was getting a 'process is bad' warning here is the link: http://stackoverflow.com/questions/...base-to-show-on-widget-not-getting-a-response
I chucked the code I've used in the link.
Maybe you could provide some input there? I have been given one answer that I will now look at.
Thanks for helping as well!
Edit: For what it's worth I'm happy to make this project fully opensource once it works for others who want to do the same thing.
I cannot see the link.
EDIT: Thanks.
RED_ said:
I am using the AppWidgetProvider to carry on my database query, within the onUpdate method. I have posted my code in the link below, on a question I asked on SO.
Since my last post I have actually done something similar to this, if not the exact same thing. I had to post a question to stack overflow because I was getting a 'process is bad' warning here is the link: http://stackoverflow.com/questions/...base-to-show-on-widget-not-getting-a-response
I chucked the code I've used in the link.
Maybe you could provide some input there? I have been given one answer that I will now look at.
Thanks for helping as well!
Edit: For what it's worth I'm happy to make this project fully opensource once it works for others who want to do the same thing.
Click to expand...
Click to collapse
Hmm, two things to try is first, uninstall, reboot, install. Sounds obvious but sometimes Eclipse/Android does weird things and a number of Google results suggest this fixes it. Secondly try adding android:label="@string/app_name" to you application tag in the manifest as per here.
If that doesn't work let us know, I think I have an idea of what else it could be but let's see..
crazyfool_1 said:
Hmm, two things to try is first, uninstall, reboot, install. Sounds obvious but sometimes Eclipse/Android does weird things and a number of Google results suggest this fixes it. Secondly try adding android:label="@string/app_name" to you application tag in the manifest as per here.
If that doesn't work let us know, I think I have an idea of what else it could be but let's see..
Click to expand...
Click to collapse
Weird, I'm getting a force close after uninstalling rebooting and installing. Here is the logcat:
Code:
05-01 18:07:02.480: E/AndroidRuntime(2546): FATAL EXCEPTION: main
05-01 18:07:02.480: E/AndroidRuntime(2546): java.lang.RuntimeException: Unable to start receiver com.test.application.TestWidget: java.lang.NullPointerException
05-01 18:07:02.480: E/AndroidRuntime(2546): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2383)
05-01 18:07:02.480: E/AndroidRuntime(2546): at android.app.ActivityThread.access$1500(ActivityThread.java:141)
05-01 18:07:02.480: E/AndroidRuntime(2546): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
05-01 18:07:02.480: E/AndroidRuntime(2546): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 18:07:02.480: E/AndroidRuntime(2546): at android.os.Looper.loop(Looper.java:137)
05-01 18:07:02.480: E/AndroidRuntime(2546): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 18:07:02.480: E/AndroidRuntime(2546): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 18:07:02.480: E/AndroidRuntime(2546): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 18:07:02.480: E/AndroidRuntime(2546): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 18:07:02.480: E/AndroidRuntime(2546): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 18:07:02.480: E/AndroidRuntime(2546): at dalvik.system.NativeStart.main(Native Method)
05-01 18:07:02.480: E/AndroidRuntime(2546): Caused by: java.lang.NullPointerException
05-01 18:07:02.480: E/AndroidRuntime(2546): at com.test.application.TestWidget.updateWidgetContent(TestWidget.java:27)
05-01 18:07:02.480: E/AndroidRuntime(2546): at com.test.application.TestWidget.onUpdate(TestWidget.java:22)
05-01 18:07:02.480: E/AndroidRuntime(2546): at android.appwidget.AppWidgetProvider.onReceive(AppWidgetProvider.java:66)
05-01 18:07:02.480: E/AndroidRuntime(2546): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2376)
05-01 18:07:02.480: E/AndroidRuntime(2546): ... 10 more
Edit: My manifest already has android:label="@string/app_name" in the application tag and the receiver tag.
RED_ said:
Weird, I'm getting a force close after uninstalling rebooting and installing. Here is the logcat:
...
Edit: My manifest already has android:label="@string/app_name" in the application tag and the receiver tag.
Click to expand...
Click to collapse
Your dbHelper is null. You have DBHelper dbhelper; but it's never initialized.
crazyfool_1 said:
Your dbHelper is null. You have DBHelper dbhelper; but it's never initialized.
Click to expand...
Click to collapse
You see I thought I fixed that by putting in the last method.
Code:
private static DBHelper getDatabaseHelper(Context context) { }
I might revert back to what I had before. I'll see what I can do.
RED_ said:
You see I thought I fixed that by putting in the last method.
Code:
private static DBHelper getDatabaseHelper(Context context) { }
I might revert back to what I had before. I'll see what I can do.
Click to expand...
Click to collapse
That might work but you haven't called it correctly.. It should be something like the following (untested):
Code:
public static void updateWidgetContent(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
dbhelper = getDatabaseHelper(context);
dbhelper.openDatabase();
String name = "basestring";
Cursor c = dbHelper.getReadableDatabase().rawQuery("SELECT * FROM websites ORDER BY RANDOM()", null);
name = c.getString(c.getColumnIndex("weburl"));
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.main);
remoteView.setTextViewText(R.id.TextView1, name);
dbhelper.close();
appWidgetManager.updateAppWidget(appWidgetIds, remoteView);
}
crazyfool_1 said:
That might work but you haven't called it correctly.. It should be something like the following (untested):
Code:
public static void updateWidgetContent(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
dbhelper = getDatabaseHelper(context);
dbhelper.openDatabase();
String name = "basestring";
Cursor c = dbHelper.getReadableDatabase().rawQuery("SELECT * FROM websites ORDER BY RANDOM()", null);
name = c.getString(c.getColumnIndex("weburl"));
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.main);
remoteView.setTextViewText(R.id.TextView1, name);
dbhelper.close();
appWidgetManager.updateAppWidget(appWidgetIds, remoteView);
}
Click to expand...
Click to collapse
i can't tell if this is progress or not. I have a new error. Cannot open the database.
Code:
05-01 18:33:57.510: E/AndroidRuntime(3440): FATAL EXCEPTION: main
05-01 18:33:57.510: E/AndroidRuntime(3440): java.lang.RuntimeException: Unable to start receiver com.test.application.TestWidget: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2383)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.app.ActivityThread.access$1500(ActivityThread.java:141)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.os.Looper.loop(Looper.java:137)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 18:33:57.510: E/AndroidRuntime(3440): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 18:33:57.510: E/AndroidRuntime(3440): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 18:33:57.510: E/AndroidRuntime(3440): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 18:33:57.510: E/AndroidRuntime(3440): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 18:33:57.510: E/AndroidRuntime(3440): at dalvik.system.NativeStart.main(Native Method)
05-01 18:33:57.510: E/AndroidRuntime(3440): Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
05-01 18:33:57.510: E/AndroidRuntime(3440): at com.text.database.DBHelper.openDatabase(DBHelper.java:62)
05-01 18:33:57.510: E/AndroidRuntime(3440): at com.test.application.TestWidget.getDatabaseHelper(TestWidget.java:45)
05-01 18:33:57.510: E/AndroidRuntime(3440): at com.test.application.TestWidget.updateWidgetContent(TestWidget.java:26)
05-01 18:33:57.510: E/AndroidRuntime(3440): at com.test.application.TestWidget.onUpdate(TestWidget.java:21)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.appwidget.AppWidgetProvider.onReceive(AppWidgetProvider.java:66)
05-01 18:33:57.510: E/AndroidRuntime(3440): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2376)
05-01 18:33:57.510: E/AndroidRuntime(3440): ... 10 more
I'm about to clean my project and do an uninstall reboot install.
RED_ said:
i can't tell if this is progress or not. I have a new error. Cannot open the database.
...
I'm about to clean my project and do an uninstall reboot install.
Click to expand...
Click to collapse
A new error is always progress ha ha
It looks like there's a problem with your openDatabase method, best bet would be to set some breakpoints and see where it falls over..
crazyfool_1 said:
A new error is always progress ha ha
It looks like there's a problem with your openDatabase method, best bet would be to set some breakpoints and see where it falls over..
Click to expand...
Click to collapse
I guess so! Thing is a copied the openDatabase method from another project of mine where it works just fine.
It's fairly straightforward in that sense.
Code:
public void openDatabase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
Edit: The crap thing is that there is not a single open source project out there that helps me with this, that I can find anyway. I'm definitely making this open source if I can get it to work.
Here is my DB class that I use. I stripped alot of my functions out but left some to show how I access the DB.
To Call from any activity:
Code:
DBAdapter db = new DBAdapter(this);
db.open();
db.AnyFunctionYouCreate();
db.close();
Code:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "YourAppName";
private static final int DATABASE_VERSION = 4; //(increased 6/13)increase this when changing db layout
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
[user=439709]@override[/user]
public void onCreate(SQLiteDatabase db)
{
db.execSQL("SQL_TO_CREATE_TABLES_HERE");
}
[user=439709]@override[/user]
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS your_table");
onCreate(db);
}
}
public Cursor lastId() {
Cursor yCursor = db.rawQuery("SELECT last_insert_rowid();", null);
if (yCursor != null){
yCursor.moveToFirst();
}
return yCursor;
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---retrieves all responses---
public Cursor getCustomResponse(String number)
{
Cursor cur = db.rawQuery("SELECT " + REP_RESPONSE +
" from " + MY_REPLIES + " where " + REP_AUDIENCE + " = " + number ,new String [] {});
return cur;
/*return db.query(MY_REPLIES, new String[] {
KEY_ROWID,
REP_RESPONSE,
REP_AUDIENCE},
null,
null,
null,
null,
null);*/
}
public Cursor getSetting(String what_table, String what_item)
{
Cursor cur = db.rawQuery("SELECT " + what_item +
" from " + what_table ,new String [] {});
return cur;
}
/**
* Updates Settings Table
*
* [user=955119]@param[/user] long RowId
* [user=955119]@param[/user] String Response
* [user=955119]@param[/user] String LocationStatus
* [user=955119]@param[/user] String LocationPassword
* [user=955119]@param[/user] String TTSStatus
* [user=955119]@param[/user] String VoiceReply
* [user=955119]@param[/user] String AppendMsg
* [user=955119]@param[/user] String NoReplyTimer
* [user=2056652]@return[/user] boolean
*/
public boolean updateSetting(long rowId, String settingResponse,
String locatorStatus, String locatorPass, String tts, String reply, String msgAppend, String timeDelay,
String auto, String silent, String shake)
{
ContentValues initialValues = new ContentValues();
initialValues.put(BUT_RESPONSE, settingResponse);
initialValues.put(BUT_LOCATOR, locatorStatus);
initialValues.put(BUT_LOC_PASS, locatorPass);
initialValues.put(BUT_TTS, tts);
initialValues.put(BUT_VOICE, reply);
initialValues.put(BUT_APPEND, msgAppend);
initialValues.put(BUT_TIME, timeDelay);
initialValues.put(BUT_AUTO_OFF, auto);
initialValues.put(BUT_SILENT, silent);
initialValues.put(BUT_SHAKE, shake);
return db.update(BUTLER_SETTINGS, initialValues,
KEY_ROWID + "=" + rowId, null) > 0;
}
public void emptySmsLog(){
db.execSQL("DELETE FROM sms_log;");
}
}
zalez said:
Here is my DB class that I use. I stripped alot of my functions out but left some to show how I access the DB.
To Call from any activity:
Code:
DBAdapter db = new DBAdapter(this);
db.open();
db.AnyFunctionYouCreate();
db.close();
Code:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "YourAppName";
private static final int DATABASE_VERSION = 4; //(increased 6/13)increase this when changing db layout
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
[user=439709]@override[/user]
public void onCreate(SQLiteDatabase db)
{
db.execSQL("SQL_TO_CREATE_TABLES_HERE");
}
[user=439709]@override[/user]
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS your_table");
onCreate(db);
}
}
public Cursor lastId() {
Cursor yCursor = db.rawQuery("SELECT last_insert_rowid();", null);
if (yCursor != null){
yCursor.moveToFirst();
}
return yCursor;
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---retrieves all responses---
public Cursor getCustomResponse(String number)
{
Cursor cur = db.rawQuery("SELECT " + REP_RESPONSE +
" from " + MY_REPLIES + " where " + REP_AUDIENCE + " = " + number ,new String [] {});
return cur;
/*return db.query(MY_REPLIES, new String[] {
KEY_ROWID,
REP_RESPONSE,
REP_AUDIENCE},
null,
null,
null,
null,
null);*/
}
public Cursor getSetting(String what_table, String what_item)
{
Cursor cur = db.rawQuery("SELECT " + what_item +
" from " + what_table ,new String [] {});
return cur;
}
/**
* Updates Settings Table
*
* [user=955119]@param[/user] long RowId
* [user=955119]@param[/user] String Response
* [user=955119]@param[/user] String LocationStatus
* [user=955119]@param[/user] String LocationPassword
* [user=955119]@param[/user] String TTSStatus
* [user=955119]@param[/user] String VoiceReply
* [user=955119]@param[/user] String AppendMsg
* [user=955119]@param[/user] String NoReplyTimer
* [user=2056652]@return[/user] boolean
*/
public boolean updateSetting(long rowId, String settingResponse,
String locatorStatus, String locatorPass, String tts, String reply, String msgAppend, String timeDelay,
String auto, String silent, String shake)
{
ContentValues initialValues = new ContentValues();
initialValues.put(BUT_RESPONSE, settingResponse);
initialValues.put(BUT_LOCATOR, locatorStatus);
initialValues.put(BUT_LOC_PASS, locatorPass);
initialValues.put(BUT_TTS, tts);
initialValues.put(BUT_VOICE, reply);
initialValues.put(BUT_APPEND, msgAppend);
initialValues.put(BUT_TIME, timeDelay);
initialValues.put(BUT_AUTO_OFF, auto);
initialValues.put(BUT_SILENT, silent);
initialValues.put(BUT_SHAKE, shake);
return db.update(BUTLER_SETTINGS, initialValues,
KEY_ROWID + "=" + rowId, null) > 0;
}
public void emptySmsLog(){
db.execSQL("DELETE FROM sms_log;");
}
}
Click to expand...
Click to collapse
Thanks, just got around to finding some time. Do you think I need to implement all of that for what I need? Obviously changing the actual calls to the database. Also DATABASE_NAME = "YourAppName" should be where your database name goes not your app name right? Or have I got that wrong?
You would be the only one to decide if you need all of that class. I reuse it in many apps for database purposes. That class is what I use with my widget provider. DATABASE_NAME is for your app name. Because when your app creates a database in the system/data area, it is stored by appname.
RED_ said:
Thanks, just got around to finding some time. Do you think I need to implement all of that for what I need? Obviously changing the actual calls to the database. Also DATABASE_NAME = "YourAppName" should be where your database name goes not your app name right? Or have I got that wrong?
Click to expand...
Click to collapse
zalez said:
You would be the only one to decide if you need all of that class. I reuse it in many apps for database purposes. That class is what I use with my widget provider. DATABASE_NAME is for your app name. Because when your app creates a database in the system/data area, it is stored by appname.
Click to expand...
Click to collapse
Ok, well it's telling me it can't find a table called "websites" in my database. I know for sure there it's there. This is annoying.
Here's the code I used from yours in my DBAdapter: http://pastebin.com/v0CWcr3t
and how I called it in my widget provider: http://pastebin.com/LDmvASdK
EDIT: I think the error is because I have my database in my assets folder and we are not copying it to the data/data folder.

JSON array problem

I used the application in the tutorial here(how to connect android with mySQL throw PHP) and it worked pretty well.
I wanted to try to make a easy social/blog as twitter, where the user input a post and it saves up in the DB, and this part works. The problem is that i also want to view all the post already posted in the application.
But it crash and i cant understand why:
Code:
package com.example.android;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends Activity {
Button buttonGetData = null;
TextView textViewUser = null;
TextView textViewMessage = null;
TextView textViewDate= null;
EditText editTextMessage = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGetData = (Button) findViewById(R.id.buttonGetData);
textViewUser = (TextView) findViewById(R.id.textViewUser);
textViewMessage = (TextView) findViewById(R.id.textViewMessage);
textViewDate = (TextView) findViewById(R.id.textViewDate);
editTextMessage = (EditText) findViewById(R.id.editTextMessage);
buttonGetData.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
//Get the data
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
String message;
message = editTextMessage.getText().toString();
DoPOST mDoPOST = new DoPOST(MainActivity.this, message, mydate);
mDoPOST.execute("");
buttonGetData.setEnabled(false);
}
});
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class DoPOST extends AsyncTask <String,Void,Boolean>{
Context mContext = null;
String strMessage = "";
String strDate = "";
String[] resUser;
String[] resMessage;
String[] resDate;
DoPOST(Context context, String Message, String mydate){
mContext = context;
strMessage = Message;
strDate = mydate;
}
Exception exception = null;
[user=439709]@override[/user]
protected Boolean doInBackground(String... arg0) {
try{
//Setup the parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("User", "Daniel"));
nameValuePairs.add(new BasicNameValuePair("Message", strMessage));
nameValuePairs.add(new BasicNameValuePair("Date", strDate));
//Add more parameters as necessary
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://deeniel.altervista.org/blog.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONArray jObject = new JSONArray(result);
for (int i = 0; i < jObject.length(); i++) {
JSONObject menuObject = jObject.getJSONObject(i);
//resUser[i] = menuObject.getString("User");
resMessage[i] = menuObject.getString("Message");
//resDate[i] = menuObject.getString("Date");
}
}
catch(Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return null;
}
[user=439709]@override[/user]
protected void onPostExecute(Boolean valid){
//Update the UI
// textViewUser.setText(resUser[0]);
textViewMessage.setText(resMessage[0]);
// textViewDate.setText(resDate[0]);
buttonGetData.setEnabled(true);
if(exception != null){
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
In the for loop i also tried instead of adding the json array into a string[]like this:
resMessage = menuObject.getString("Message");
i also tryied withoth a string array, by concatenating inside the for:
resMessage = resMessage + menuObject.getString("Message");
And it doesnt give me any problem to save all the array inside and show it up in the textView.
SO why like this it crash?
Code:
07-06 09:07:49.815 19475-19589/com.example.android E/ClientServerDemo: Error:
java.lang.NullPointerException
at com.example.android.MainActivity$DoPOST.doInBackground(MainActivity.java:130)
at com.example.android.MainActivity$DoPOST.doInBackground(MainActivity.java:77)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
07-06 09:07:49.815 19475-19475/com.example.android E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.android.MainActivity$DoPOST.onPostExecute(MainActivity.java:151)
at com.example.android.MainActivity$DoPOST.onPostExecute(MainActivity.java:77)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5226)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
don't you need to initialize resMessage before you use it?
Code:
resMessage = new String[jObject.length()]
I use Google's gson library for JSON. I think it is much easier.

[Q] Need help with my next update!

Right before i start, i have looked absolutely everywhere for the answer but there's only so much that people talk about so this is my last hope because I've tried and tried but simply can't do it!
Now i understand that to some this may be a very very easy thing to do and although i have learnt a hell of a lot since i started developing, I'm just not a pro (Just yet)
So basically ever since i started my music player, I've had one big problem and that's trying to list music albums and the songs, now, I have code that does work but it simply doesn't go with my apps data source so I'm trying to the code that i done but the code that I done doesn't show the list of songs, becauser it crashes
Here's the code so far:
Code:
public class AlbumsList extends ListActivity{
public ArrayList<HashMap<String,String>> albumsList = new ArrayList<HashMap<String, String>>();
ListView musiclist;
int songAlbum;
int count;
int songPath;
private Cursor cursor;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.albums);
ArrayList<HashMap<String, String>> albumListData = new ArrayList<HashMap<String, String>>();
final AlbumsList plm = new AlbumsList();
// get all songs from sdcard
this.albumsList = plm.getPlayList(this, count);
// looping through playlist
for (int i = 0; i < albumsList.size(); i++) {
// creating new HashMap
HashMap<String, String> album = albumsList.get(i);
// adding HashList to ArrayList
albumListData.add(album);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, albumListData,
android.R.layout.simple_list_item_1, new String[] { "songAlbum", "songTitle", "orderBy", "songPath", "where", "whereVal" }, new int[] {
android.R.id.text1});
setListAdapter(adapter);
}
public ArrayList<HashMap<String, String>> getPlayList(Context c, int position) {
final String[] columns = { BaseColumns._ID,
AlbumColumns.ALBUM };
final Cursor mCursor = c.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
columns, null, null, null);
String songAlbum = "";
if (mCursor.moveToFirst()) {
do {
mCursor.getString(mCursor.getColumnIndexOrThrow(BaseColumns._ID));
songAlbum = mCursor.getString(mCursor.getColumnIndexOrThrow(AudioColumns.ALBUM));
HashMap<String, String> album = new HashMap<String, String>();
album.put("songAlbum", songAlbum);
albumsList.add(album);
} while (mCursor.moveToNext());
}
return albumsList;
}
@Override
protected void onListItemClick(ListView lv, View v, int position, long id) {
if(cursor.moveToPosition(position)){
cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaColumns.TITLE, MediaColumns.DATA, AudioColumns.ALBUM, BaseColumns._ID }, null, null,
"LOWER(" + MediaColumns.TITLE + ") ASC");
String where = AudioColumns.ALBUM
+ "=?";
String whereVal = cursor.getString(cursor.getColumnIndex(AlbumColumns.ALBUM));
String orderBy = MediaColumns.TITLE;
String songTitle = MediaColumns.TITLE;
String songPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA));
HashMap<String, String> album = new HashMap<String, String>();
album.put("songTitle", songTitle);
album.put("where", where);
album.put("whereVal", whereVal);
album.put("orderBy", orderBy);
album.put("songPath", songPath);
albumsList.add(album);
}else{
}
}
}
That Code successfully gets all the albums but it won't get the songs from the selected album
Here's the LogCat:
Code:
03-18 18:42:21.579: E/AndroidRuntime(10214): at dalvik.system.NativeStart.main(Native Method)
03-18 18:46:48.223: E/SpannableStringBuilder(12325): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-18 18:46:48.223: E/SpannableStringBuilder(12325): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-18 18:46:48.894: E/AndroidRuntime(12325): FATAL EXCEPTION: main
03-18 18:46:48.894: E/AndroidRuntime(12325): java.lang.NullPointerException
03-18 18:46:48.894: E/AndroidRuntime(12325): at com.simplistic.simplisticmusicfree.AlbumsList.onListItemClick(AlbumsList.java:93)
03-18 18:46:48.894: E/AndroidRuntime(12325): at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
03-18 18:46:48.894: E/AndroidRuntime(12325): at android.widget.AdapterView.performItemClick(AdapterView.java:301)
03-18 18:46:48.894: E/AndroidRuntime(12325): at android.widget.AbsListView.performItemClick(AbsListView.java:1519)
03-18 18:46:48.894: E/AndroidRuntime(12325): at android.widget.AbsListView$PerformClick.run(AbsListView.java:3291)
03-18 18:46:48.894: E/AndroidRuntime(12325): at android.widget.AbsListView$1.run(AbsListView.java:4340)
03-18 18:46:48.894: E/AndroidRuntime(12325): at android.os.Handler.handleCallback(Handler.java:725)
03-18 18:46:48.894: E/AndroidRuntime(12325): at android.os.Handler.dispatchMessage(Handler.java:92)
03-18 18:46:48.894: E/AndroidRuntime(12325): at android.os.Looper.loop(Looper.java:137)
03-18 18:46:48.894: E/AndroidRuntime(12325): at android.app.ActivityThread.main(ActivityThread.java:5328)
03-18 18:46:48.894: E/AndroidRuntime(12325): at java.lang.reflect.Method.invokeNative(Native Method)
03-18 18:46:48.894: E/AndroidRuntime(12325): at java.lang.reflect.Method.invoke(Method.java:511)
03-18 18:46:48.894: E/AndroidRuntime(12325): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
03-18 18:46:48.894: E/AndroidRuntime(12325): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
03-18 18:46:48.894: E/AndroidRuntime(12325): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:126)
03-18 18:46:48.894: E/AndroidRuntime(12325): at dalvik.system.NativeStart.main(Native Method)
Also just in case your wondering, this is music player in question: https://play.google.com/store/apps/details?id=com.simplistic.simplisticmusicfree
So yeah please for the love of god, help!!!
Updated the Question!
AmatuerAppDeveloper said:
Updated the Question!
Click to expand...
Click to collapse
Sorry but there seems to be a few simple problems there, and the error tells you what it is. I would suspect that the tutorials you have followed have not done a great job, or that you skipped some quite basic things... maybe learn some Java 101 and android basics. BTW I don't mean to sound condescending, I'm actually an authorised Autodesk instructor and developer and artist/trainer so it's maybe the way I say things, it's often for the total benefit of the individual I'm talking to, and quite blunt sometimes.
Your problem is clear and outlined in that error,
Code:
03-18 18:46:48.894: E/AndroidRuntime(12325): java.lang.NullPointerException
03-18 18:46:48.894: E/AndroidRuntime(12325): at com.simplistic.simplisticmusicfree.AlbumsList.onListItemClick(AlbumsList.java:93)
so on line 93, you are asking an "Object" that is actually "NULL" to execute or reference data or method, I would guess that it is as simple as the
Code:
private Cursor cursor;
You never assign it anything, you just create a null reference there. But then you ask it (Being null at this point) to ".moveToPosition()"
BTW: Still not fully awake and only glimpsed at your post
deanwray said:
Sorry but there seems to be a few simple problems there, and the error tells you what it is. I would suspect that the tutorials you have followed have not done a great job, or that you skipped some quite basic things... maybe learn some Java 101 and android basics. BTW I don't mean to sound condescending, I'm actually an authorised Autodesk instructor and developer and artist/trainer so it's maybe the way I say things, it's often for the total benefit of the individual I'm talking to, and quite blunt sometimes.
Your problem is clear and outlined in that error,
Code:
03-18 18:46:48.894: E/AndroidRuntime(12325): java.lang.NullPointerException
03-18 18:46:48.894: E/AndroidRuntime(12325): at com.simplistic.simplisticmusicfree.AlbumsList.onListItemClick(AlbumsList.java:93)
so on line 93, you are asking an "Object" that is actually "NULL" to execute or reference data or method, I would guess that it is as simple as the
Code:
private Cursor cursor;
You never assign it anything, you just create a null reference there. But then you ask it (Being null at this point) to ".moveToPosition()"
BTW: Still not fully awake and only glimpsed at your post
Click to expand...
Click to collapse
Thanks for the reply, I'll have to re look the code and see what I can do, also I'd like to note that I downloaded your beta app and I have to say it certainly looks promising, so im looking forward to official release
AmatuerAppDeveloper said:
Thanks for the reply, I'll have to re look the code and see what I can do, also I'd like to note that I downloaded your beta app and I have to say it certainly looks promising, so im looking forward to official release
Click to expand...
Click to collapse
Thanks for the download Yeah well my 1st app, and still a number of months away from what I would call "releasable".. Need to get all the user in app theming ability in there

[Q] App crashing at loading setContentView

I am writing a simple about android app that posts a status on your Facebook wall, and I am getting a crash caused by setContentView. I set up the Facebook API correctly I believe, but I am still getting a crash. Below is all of the code.
activity_main.java:
Java:
package com.rakesh.itijgm;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
public class MainActivity extends Activity {
private static String APP_ID = "443967745743818";
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); [COLOR="Red"][B]//THE APP CRASHES HERE[/B][/COLOR]
Button btn_fb_login = (Button) findViewById(R.id.btn_fb_login);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btn_fb_login.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View view) {
loginToFacebook();
}
});
}
//fb_login
public void loginToFacebook(){
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null){
facebook.setAccessToken(access_token);
}
if (expires != 0){
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()){
facebook.authorize(this,
new String[]{"email", "publish_stream"},
new Facebook.DialogListener() {
[user=439709]@override[/user]
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",facebook.getAccessExpires());
editor.commit();
}
[user=439709]@override[/user]
public void onFacebookError(FacebookError fberror) {
}
[user=439709]@override[/user]
public void onError(DialogError error) {
}
[user=439709]@override[/user]
public void onCancel() {
}
});
}}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I also have my Stack trace:
PHP:
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.widget.LoginButton" on path: DexPathList[[zip file "/data/app/com.rakesh.itijgm-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.rakesh.itijgm-1, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
at android.view.LayoutInflater.createView(LayoutInflater.java:559)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631)
at android.view.LayoutInflater.inflate(Native Method)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:343)
at android.app.Activity.setContentView(Activity.java:1936)
at com.rakesh.itijgm.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:5313)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2276)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
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:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
I made sure that the findViewById is referred to the correct element, and that is good, so I can't decipher the problem here.
PHP:
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.widget.LoginButton" on path: DexPathList[[zip file "/data/app/com.rakesh.itijgm-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.rakesh.itijgm-1, /vendor/lib, /system/lib]]
You are reading the 1st line of the exception right ? That tells you everything you probably need to ? This comment is not meaning to be sarcastic, just it's pretty hard to miss what it's saying lol
Anyways in short you are missing com.facebook.widget.LoginButton from whatever lib I assume you are using it from ... facebook maybe
deanwray said:
PHP:
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.widget.LoginButton" on path: DexPathList[[zip file "/data/app/com.rakesh.itijgm-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.rakesh.itijgm-1, /vendor/lib, /system/lib]]
You are reading the 1st line of the exception right ? That tells you everything you probably need to ? This comment is not meaning to be sarcastic, just it's pretty hard to miss what it's saying lol
Anyways in short you are missing com.facebook.widget.LoginButton from whatever lib I assume you are using it from ... facebook maybe
Click to expand...
Click to collapse
*facepalm* Thanks, do you know how I can integrate the facebook library properly, I followed the instructions on developers.facebook,com, but apparently, they don't work.
rakeshdas said:
*facepalm* Thanks, do you know how I can integrate the facebook library properly, I followed the instructions on developers.facebook,com, but apparently, they don't work.
Click to expand...
Click to collapse
well depends on build system and ide you're using, could be that the ide has reference but the build system does not... and I would not touch facebook with...well...any appendage or item!
deanwray said:
well depends on build system and ide you're using, could be that the ide has reference but the build system does not... and I would not touch facebook with...well...any appendage or item!
Click to expand...
Click to collapse
Well I am using Android Studio and well FB is using Eclipse in the tutorial, that is an eye sore, should I try switch over to eclipse to see if that fixes the problem?
rakeshdas said:
Well I am using Android Studio and well FB is using Eclipse in the tutorial, that is an eye sore, should I try switch over to eclipse to see if that fixes the problem?
Click to expand...
Click to collapse
well you need to work out why and what is not finding it... just do it logically as if for any possible missing component, and make sure compile order is correct and that gradle knows what it needs... like I say I have little experience with fb, but libs and modules are quite simple as a rule
deanwray said:
well you need to work out why and what is not finding it... just do it logically as if for any possible missing component, and make sure compile order is correct and that gradle knows what it needs... like I say I have little experience with fb, but libs and modules are quite simple as a rule
Click to expand...
Click to collapse
Do know of anyone who has a tutorial on integrating the FB API using Android Studio?
rakeshdas said:
Do know of anyone who has a tutorial on integrating the FB API using Android Studio?
Click to expand...
Click to collapse
Just download the FB SDK and unzip it. Then do a import module (File > Import module) in Android Studio and point to the unzipped sdk folder and it should work.

Http POST request not sending

I'm trying to build a simple app that sends data to Microsoft Azure IoT Central but I'm getting W/System.err: android.os.NetworkOnMainThreadException error.
Here is my code:
Java:
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends WearableActivity implements View.OnClickListener {
Button clickMeButton;
TextView textView;
int count = 0;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.click_button);
button.setOnClickListener(this);
setAmbientEnabled();
}
@Override
public void onClick(View view) {
count++;
final TextView text = (TextView) findViewById(R.id.results);
text.setText("I am clicked: "+count);
int tempValue = count;
JSONObject json = new JSONObject();
try {
json.put("Count", count);
} catch (JSONException e) {
e.printStackTrace();
}
// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("URL Link");
StringEntity params = new StringEntity(json.toString());
request.addHeader("Authorization", "SharedAccessSignature Token");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = (HttpResponse) httpClient.execute(request);
} catch (Exception ex) {
} finally {
// @Deprecated httpClient.getConnectionManager().shutdown();
Log.e("Hello", "I'm done running");
}
Here is the trace:
Code:
W/System.err: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
at java.net.InetAddress.getAllByName(InetAddress.java:1154)
at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:44)
W/System.err: at org.apache.http.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:259)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at com.example.wearazure.MainActivity.onClick(MainActivity.java:97)
at android.view.View.performClick(View.java:6599)
at android.view.View.performClickInternal(View.java:6576)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25908)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6680)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Any suggestions are appreciated, thanks!
If you network on the main thread, the UI blocks which is bad.
You need to make a separate thread and do the networking on that. Send a message back to the UI thread when you're ready to update the UI.
Eg.
Code:
final handler = new Handler();
new Thread(() -> {
// Networking...
handler.post(() -> {
// Update UI
});
}}).start();
you can also use an async task or a service (send intent, return intent) depending on your needs. They're more work but might help to split things up better.
a1291762 said:
If you network on the main thread, the UI blocks which is bad.
You need to make a separate thread and do the networking on that. Send a message back to the UI thread when you're ready to update the UI.
Eg.
Code:
final handler = new Handler();
new Thread(() -> {
// Networking...
handler.post(() -> {
// Update UI
});
}}).start();
you can also use an async task or a service (send intent, return intent) depending on your needs. They're more work but might help to split things up better.
Click to expand...
Click to collapse
Thanks so much!!

Categories

Resources