Reading a text file from res/raw folder - java

Im trying to read a text file from the raw folder in res using final Scanner input = new Scanner(new File(R.raw.xmlsource)).useDelimiter("[\\;]+"); but it isn't reading because of the resource id being int in R.java file, my code is below
EDIT Made some changes to my code below, still doesn't run but using the debugger i can tell that it actually reads the file, the problem seems to be at String[] RssLinksArray = readLine.split("[\\;]+"); where the code terminates, i can't for the life of me figure out why. i'm attaching the logcat also.
Any help would be tremendously appreciated.
package com.simplerssreader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
import java.util.Scanner;
import org.xmlpull.v1.XmlPullParserException;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
public class RssService extends IntentService
{
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService()
{
super("RssService");
}
#Override
protected void onHandleIntent(Intent intent)
{
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
while ((readLine = br.readLine()) != null)
{
}
} catch (IOException e)
{
e.printStackTrace();
}
String[] RssLinksArray = readLine.split("[\\;]+");
final String RSS_LINK = RssLinksArray[0];
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link)
{
try
{
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e)
{
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
LOGCAT
10-24 23:07:49.908: D/dalvikvm(1189): GC_FOR_ALLOC freed 101K, 9% free 2778K/3040K, paused 68ms, total 72ms
10-24 23:07:49.938: I/dalvikvm-heap(1189): Grow heap (frag case) to 3.939MB for 1127536-byte allocation
10-24 23:07:50.089: D/dalvikvm(1189): GC_FOR_ALLOC freed 2K, 7% free 3877K/4144K, paused 149ms, total 149ms
10-24 23:07:50.461: W/dalvikvm(1189): threadid=11: thread exiting with uncaught exception (group=0x41465700)
10-24 23:07:50.504: E/AndroidRuntime(1189): FATAL EXCEPTION: IntentService[RssService]
10-24 23:07:50.504: E/AndroidRuntime(1189): java.lang.NullPointerException
10-24 23:07:50.504: E/AndroidRuntime(1189): at com.simplerssreader.RssService.onHandleIntent(RssService.java:48)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Handler.dispatchMessage(Handler.java:99)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Looper.loop(Looper.java:137)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.HandlerThread.run(HandlerThread.java:61)
10-24 23:07:50.899: D/libEGL(1189): loaded /system/lib/egl/libEGL_emulation.so
10-24 23:07:50.940: D/(1189): HostConnection::get() New Host Connection established 0x2a1db628, tid 1189
10-24 23:07:51.078: D/libEGL(1189): loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-24 23:07:51.279: D/libEGL(1189): loaded /system/lib/egl/libGLESv2_emulation.so
10-24 23:07:51.699: W/EGL_emulation(1189): eglSurfaceAttrib not implemented
10-24 23:07:51.729: D/OpenGLRenderer(1189): Enabling debug mode 0
10-24 23:07:51.769: I/Choreographer(1189): Skipped 85 frames! The application may be doing too much work on its main thread.
10-24 23:07:56.358: I/Choreographer(1189): Skipped 265 frames! The application may be doing too much work on its main thread.

InputStream inputStream = getResources().openRawResource(R.raw.xmlsource);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

Related

Sending String to PHP file via android application

I am developing an app which includes the upload of all contacts to my server what i am doing is displaying all the contacts and sending them to my server as a string.Here is my code:
package com.example.core.freemusic;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MainActivity extends Activity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.LinearLayout1);
LoadContactsAyscn lca = new LoadContactsAyscn();
lca.execute();
}
class LoadContactsAyscn extends AsyncTask < Void, Void, String > {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Please Wait","");
}
#Override
protected String doInBackground(Void...params) {
String contacts = "";
Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts += contactName + ":" + phNumber + "\n";
}
c.close();
return contacts;
}
#Override
protected void onPostExecute(String contacts) {
super.onPostExecute(contacts);
pd.cancel();
TextView a = (TextView) findViewById(R.id.textView);
a.setText(contacts);
doInBackground(contacts);
}
protected void doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
try {
httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Actually the code shows no error but on running it in emulator it crashes.
the error on logcat is:
05-24 14:00:57.989 2488-2500/com.example.core.freemusic W/art﹕ Suspending all threads took: 5.841ms
05-24 14:00:57.992 2488-2500/com.example.core.freemusic I/art﹕ Background partial concurrent mark sweep GC freed 1888(115KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 502KB/1014KB, paused 6.923ms total 95.188ms
05-24 14:00:58.073 2488-2488/com.example.core.freemusic I/Choreographer﹕ Skipped 37 frames! The application may be doing too much work on its main thread.
05-24 14:00:58.080 2488-2488/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
05-24 14:00:58.102 2488-2488/com.example.core.freemusic D/AndroidRuntime﹕ Shutting down VM
05-24 14:00:58.103 2488-2488/com.example.core.freemusic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.core.freemusic, PID: 2488
java.lang.IllegalArgumentException: Illegal character in query at index 43: http://192.168.2.30/b.php?username=Sd:(546) 456-4826
Sad:486-44
at java.net.URI.create(URI.java:730)
at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:64)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-24 14:01:01.259 2488-2488/com.example.core.freemusic I/Process﹕ Sending signal. PID: 2488 SIG: 9
05-24 15:24:12.790 2685-2685/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
As error code state, you need to encode the query:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
need to changed into:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+java.net.URLEncoder.encode(params[0], "UTF-8"));

Android Socket Client Receiving data

I am creating a basic test application for android that can connect to a socket server and send and receive data. i have been able to get the sending of data from the client to the server working but seem to have a problem getting the android to receive data. the server works as i have been able to test that using a external application.
here is my code
package com.socket_sending_and_receving_test;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;
import android.widget.TextView;
import android.os.Handler;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Sending_And_Receiving extends Activity {
private Socket socket;
String message = "";
String mClientMsg;
TextView text;
final Handler myHandler = new Handler();
int count = 0;
public static String SERVERPORT;
public static int SERVERPORT2;
public static String SERVER_IP;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending_and_receaving);
text = (TextView) findViewById(R.id.textView);
text.setText("0");
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(mClientMsg);
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
String st = null;
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
{
BufferedReader input = null;
try {
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
st = reader.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void connect(View view) {
EditText ip = (EditText) findViewById(R.id.ip);
EditText port = (EditText) findViewById(R.id.port);
SERVER_IP = ip.getText().toString();
SERVERPORT = port.getText().toString();
new Thread(new ClientThread()).start();
new Thread(new CommsThread()).start();
}
public void Disconnect(View view) {
try {
socket.shutdownInput();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.ko);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
SERVERPORT2 = Integer.parseInt(SERVERPORT);
socket = new Socket(serverAddr, SERVERPORT2);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
after the connection is made the application crashes. I don't think it is due to the UI updating but i think its due to the receiving of data.
here is the logcat
07-08 21:59:57.915 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
07-08 21:59:57.920 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
07-08 21:59:57.925 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
07-08 21:59:57.930 7041-7041/com.socket_sending_and_receving_test D/﹕ Device driver API match
Device driver API version: 10
User space API version: 10
07-08 21:59:57.930 7041-7041/com.socket_sending_and_receving_test D/﹕ mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012
07-08 21:59:57.965 7041-7041/com.socket_sending_and_receving_test D/OpenGLRenderer﹕ Enabling debug mode 0
07-08 21:59:57.965 7041-7041/com.socket_sending_and_receving_test E/SensorManager﹕ thread start
07-08 21:59:57.970 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ registerListener :: handle = 0 name= LSM330DLC 3-axis Accelerometer delay= 200000 Listener= android.view.OrientationEventListener$SensorEventListenerImpl#42b1cf38
07-08 21:59:58.080 7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 21:59:58.080 7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 22:00:03.235 7041-7193/com.socket_sending_and_receving_test W/dalvikvm﹕ threadid=13: thread exiting with uncaught exception (group=0x41e792a0)
07-08 22:00:03.240 7041-7193/com.socket_sending_and_receving_test E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-2791
java.lang.NullPointerException
at com.socket_sending_and_receving_test.Sending_And_Receiving$CommsThread.run(Sending_And_Receiving.java:74)
at java.lang.Thread.run(Thread.java:856)
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ unregisterListener:: Listener= android.view.OrientationEventListener$SensorEventListenerImpl#42b1cf38
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/Sensors﹕ Remain listener = Sending .. normal delay 200ms
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test I/Sensors﹕ sendDelay --- 200000000
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ JNI - sendDelay
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test I/SensorManager﹕ Set normal delay = true
07-08 22:00:09.870 7041-7041/com.socket_sending_and_receving_test I/Choreographer﹕ Skipped 392 frames! The application may be doing too much work on its main thread.
07-08 22:00:11.680 7041-7193/com.socket_sending_and_receving_test I/Process﹕ Sending signal. PID: 7041 SIG: 9
Any help on this problem would be greatly appreciated
Cheers :)
Your socket is NULL. This is because of a race condition:
new Thread(new ClientThread()).start();
new Thread(new CommsThread()).start();
Both threads are started here, but ClientThread will initialise the socket while CommsThread tries to use it. But it is not initialised at this point.
You may call CommsThread's run() right after socket=... or if you really need a 2nd thread, start it there.
Your CommsThread is running before your ClientThread has completed the connection. So, 'socket' is still null and you get an NPE.
There is absolutely no reason for these to be two different threads. Combine them, so that the connection is made first and then the I/O starts. Using two threads to perform tasks that must be sequential is basically inane.

Android Unable to instantiate Activity(Using File Inputs)

Info: I am a decent java developer, I know my way around it pretty well I think, so I decided to give android a chance, and it hasn't been the smoothest road for me. I mess up very often. Anyway to my question if anyone would be so kind to help me out with this error I would very much appreciate it! Thank you.
Main Class
package dev.shaw.MyShoppingPlanner;
import java.io.File;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private String m_Text = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
if(firstTime()){
GenerateNeededFiles();
}
else{
//do nothing
}
ActionBar.TabListener tablistener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch(tab.getText().toString()){
case "Lists":
openLists();
break;
case "Store":
openStore();
case "Home":
openTab();
}
}
private void openTab() {
}
private void openStore() {
View v = new View(MainActivity.this);
v.setVisibility(1);
v.clearFocus();
v.bringToFront();
}
private void openLists() {
Intent intent = new Intent(MainActivity.this,List_Activity.class);
startActivity(intent);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// do nothing
}
};
actionbar.addTab(actionbar.newTab().setText("Home").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Store").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Lists").setTabListener(tablistener));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
private boolean firstTime() {
File storelist = new File(this.getFilesDir() + "\\StoreList.txt");
File listnames = new File(this.getFilesDir() + "\\ListNames.txt");
if(storelist.exists() && listnames.exists()){
return false;
}
else{
return true;
}
}
private void GenerateNeededFiles() {
Intent intent = new Intent(MainActivity.this,Install_Activity.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
default:
return super.onOptionsItemSelected(item);
}
}
private void openSettings() {
}
private void openSearch() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Search");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
The Class that gets an error when called
package dev.shaw.MyShoppingPlanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class List_Activity extends ListActivity {
String ListNames[] = getListNames();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem , ListNames));
}
protected void onListItemClick(ListView lv, View v, int pos,long id){
this.onListItemClick(lv, v, pos, id);
ShoppingList list = new ShoppingList(ListNames[pos]);
try {
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list.toArray(list.getFile())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String[] getListNames() {
File file = new File(this.getFilesDir() + "\\listnames.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStreamReader is = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(is);
String line;
String names[] = new String[100];
int i = 0;
try {
while(true){
line = br.readLine();
if(line == null){
break;
}
else{
try{
names[i] = line;
}
catch(NullPointerException e){
e.printStackTrace();
}
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return names;
}
}
and here is the printStack
03-23 04:58:16.523: D/dalvikvm(3710): GC_FOR_ALLOC freed 151K, 18% free 2770K/3356K, paused 2ms, total 7ms
03-23 04:58:16.531: D/dalvikvm(3710): GC_FOR_ALLOC freed 100K, 19% free 2988K/3680K, paused 1ms, total 4ms
03-23 04:58:16.535: I/dalvikvm-heap(3710): Grow heap (frag case) to 4.414MB for 1127532-byte allocation
03-23 04:58:16.539: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 3ms, total 3ms
03-23 04:58:16.555: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 1ms, total 1ms
03-23 04:58:16.587: I/dalvikvm-heap(3710): Grow heap (frag case) to 6.833MB for 2536932-byte allocation
03-23 04:58:16.599: D/dalvikvm(3710): GC_FOR_ALLOC freed 0K, 10% free 6567K/7264K, paused 2ms, total 2ms
03-23 04:58:16.615: D/HardwareRenderer(3710): Profiling hardware renderer
03-23 04:58:16.647: D/libEGL(3710): loaded /system/lib/egl/libEGL_genymotion.so
03-23 04:58:16.651: D/(3710): HostConnection::get() New Host Connection established 0xb85b3b40, tid 3710
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv2_genymotion.so
03-23 04:58:16.711: W/EGL_genymotion(3710): eglSurfaceAttrib not implemented
03-23 04:58:16.711: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from GradienCache
03-23 04:58:16.723: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
03-23 04:58:16.723: D/OpenGLRenderer(3710): Enabling debug mode 0
03-23 04:58:18.015: D/AndroidRuntime(3710): Shutting down VM
03-23 04:58:18.015: W/dalvikvm(3710): threadid=1: thread exiting with uncaught exception (group=0xa4bae648)
03-23 04:58:18.015: E/AndroidRuntime(3710): FATAL EXCEPTION: main
03-23 04:58:18.015: E/AndroidRuntime(3710): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{dev.shaw.MyShoppingPlanner/dev.shaw.MyShoppingPlanner.List_Activity}: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Handler.dispatchMessage(Handler.java:99)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Looper.loop(Looper.java:137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invokeNative(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invoke(Method.java:525)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dalvik.system.NativeStart.main(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): Caused by: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.content.ContextWrapper.getFilesDir(ContextWrapper.java:199)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.getListNames(List_Activity.java:38)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.<init>(List_Activity.java:16)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstanceImpl(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstance(Class.java:1130)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
03-23 04:58:18.015: E/AndroidRuntime(3710): ... 11 more

Android unable to add getByName

I'm trying to add getByName to get the IP address of a hostname and use it in my POST command
the problem is wherever i insert this code it crashes
i tried to insert in doInBackground it also crashes So where should i insert it ??
package com.example.loginad;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Logindb extends Activity {
Button login;
EditText u,p;
TextView res;
String result;
String x="mobile";
String host;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logindb);
login=(Button)findViewById(R.id.login);
u=(EditText)findViewById(R.id.u);
p=(EditText)findViewById(R.id.p);
res=(TextView)findViewById(R.id.res);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyAsyncTask().execute(u.getText().toString(),p.getText().toString());
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
boolean success = postData(params[0],params[1]);
try
{
InetAddress address=null;
address = InetAddress.getByName("Nicky-PC");
host=address.getHostAddress();
}
catch(Exception e)
{
e.printStackTrace();
}
return success;
}
protected void onPostExecute(Boolean localres){
if (localres){
res.setText("A Correct Username and Password");
}else{
res.setText("Incorrect Username or Password");
}
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
//Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
}
/*public void ObtainHost()
{
try
{
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} */
public Boolean postData(String a,String b) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", a));
postParameters.add(new BasicNameValuePair("password", b));
postParameters.add(new BasicNameValuePair("mobileid",x));
// String valid = "1";
String response = null;
try {
// Toast.makeText(getApplicationContext(), host.toString(), Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost("http://"+host+"/new/check.php",postParameters);
//now in result you will have the response from php file either 0 or 1.
result = response.toString();
// res = res.trim();
result = result.replaceAll("\\s+", "");
// error.setText(res);
} catch (Exception e) {
res.setText(e.toString());
}
return result.equals("1");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logindb, menu);
return true;
}
}
Stacktrace
11-26 21:28:37.856: D/libEGL(17150): loaded /system/lib/egl/libEGL_genymotion.so
11-26 21:28:37.876: D/(17150): HostConnection::get() New Host Connection established 0xb8ed35a8, tid 17150
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv2_genymotion.so
11-26 21:28:37.968: W/EGL_genymotion(17150): eglSurfaceAttrib not implemented
11-26 21:28:37.976: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from GradienCache
11-26 21:28:37.996: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
11-26 21:28:37.996: D/OpenGLRenderer(17150): Enabling debug mode 0
11-26 21:28:44.876: W/dalvikvm(17150): threadid=13: thread exiting with uncaught exception (group=0xa4c1f648)
11-26 21:28:44.920: E/AndroidRuntime(17150): FATAL EXCEPTION: AsyncTask #3
11-26 21:28:44.920: E/AndroidRuntime(17150): java.lang.RuntimeException: An error occured while executing doInBackground()
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.lang.Thread.run(Thread.java:841)
11-26 21:28:44.920: E/AndroidRuntime(17150): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:837)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:358)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.checkForRelayout(TextView.java:6524)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3771)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3629)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3604)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.postData(Logindb.java:130)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:70)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:1)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-26 21:28:44.920: E/AndroidRuntime(17150): ... 4 more
11-26 21:28:44.932: D/dalvikvm(17150): GC_FOR_ALLOC freed 259K, 5% free 6365K/6660K, paused 8ms, total 8ms
First if you will use AsyncHttpClient then you do not need AsyncTask but if you will use HttpClient then you need AsyncTask task.
the below code is part from working code to execute get and post requests. Modify it as your need
#Override
protected String doInBackground(String... params) {
backGroundExecuted = false;
Log.d("doInBackground", "Start processing doInBackground");
HttpClient httpClient = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
if (httpMethodType == null || url == null) {
Log.d("doInBackground" , "The URL and Method Type is mandatory, cannot be null - httpMethodType =" + httpMethodType + " and url =" + url);
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("The URL and Method Type is mandatory, cannot be null");
return null;
}
try {
//set timeout
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = null;
if (httpMethodType.equals(HTTPMethodType.POST.toString())) {
httpPost = new HttpPost(url);
//setting json object to request.
if (postParams != null) {
AbstractHttpEntity entity = null;
entity = new ByteArrayEntity(postParams.getBytes("UTF8"));
if (httpContentType != null) {
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, httpContentType));
}
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
} else if (httpMethodType.equals(HTTPMethodType.GET.toString()) || httpMethodType.equals(HTTPMethodType.PUT.toString())) {
if (queryParams != null) {
url = url + "?" + URLEncodedUtils.format(queryParams, "utf-8");
Log.d(TAG ,"new URL :" + url);
}
httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
this.getApiResponse().setResponseCode(httpResponse.getStatusLine().getStatusCode());
this.getApiResponse().setResponseDescription(httpResponse.getStatusLine().getReasonPhrase());
if (this.getApiResponse().getResponseCode() != HttpStatus.SC_OK) {
this.getApiResponse().setSuccess(false);
Log.w(getClass().getSimpleName(),
"Error " + this.getApiResponse().getResponseCode() + " for URL " + url);
Log.w(getClass().getSimpleName(),
"Error " + this.getApiResponse().getResponseDescription() + " for URL " + url);
}
Log.d("doInBackground", "The API call executed and will check the response");
HttpEntity entityResp = httpResponse.getEntity();
if (entityResp != null) {
this.getApiResponse().setResponse(appHelper.getStringFromInputStream(entityResp.getContent()));
Log.d("doInBackground","The response is :" + this.getApiResponse().getResponse());
this.getApiResponse().setSuccess(true);
}
} catch (UnsupportedEncodingException e1) {
Log.e("doInBackground","Exception :" + e1.toString());
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("Exception :" + e1.toString());
Log.e("doInBackground","Exception :" + e1.toString());
e1.printStackTrace();
} catch (Exception e) {
Log.e("doInBackground","Exception :" + e.toString());
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("Exception :" + e.toString());
if (httpPost != null && !httpPost.isAborted()) {
httpPost.abort();
}
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
backGroundExecuted = true;
}
return null;
}

Android application unable to run on emulator

I'm quite new to android development, I'm trying to develop a server-client application where the server is a simple java application that reads some text from a file and sends it using output stream. the client is an android application that reads this stream when clicking a button and displays it on a text view.
I'm using eclipse with ADK, and testing on an emulator here's how both codes look like:
Server:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server {
/**
* #param args
* #throws IOException
* #throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException
{
System.out.println("***********Starting ***********");
ServerSocket servsock = new ServerSocket(12344);
System.out.println("Waiting...");
Socket sock = servsock.accept();
while (true)
{
System.out.println("Accepted connection : " + sock);
File myFile = new File ("source.txt");
while (true){
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
}
}
}
Client:
-MainActivity
package com.example.streamerclient;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button ConnectBtn ;
#Override
public void onResume() {
super.onResume();
//setContentView(R.layout.activity_main);
System.out.println(" on resume ");
ConnectBtn = (Button)findViewById(R.id.ConnectButton);
ConnectBtn.setOnClickListener(this);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Connecting c = new Connecting();
}
}
-Connecting class
package com.example.streamerclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.widget.TextView;
public class Connecting extends Activity implements Runnable
{
private Socket sock;
private BufferedReader r;
private BufferedWriter out;
TextView Data;
public Connecting ()
{
Data = (TextView) findViewById(R.id.DataTextView);
Thread th = new Thread(this);
th.start();
}
#Override
public void run() {
try
{
System.out.println("trying to initiated ");
Data.setText("trying to initiated ");
sock = new Socket("10.0.2.2",12344);
System.out.println(" socket initiated ");
Data.setText(" socket initiated ");
r = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Data.setText(" buffer reader initiated ");
System.out.println(" buffer reader initiated ");
out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
Data.setText(" buffer writer initiated ");
System.out.println(" buffer writer initiated ");
final String data = r.readLine();
Data.setText(" Data read is: \n"+data);
System.out.println(" Data read is: \n"+data);
}
catch (IOException ioe) { }
}
public void OnPause()
{
System.out.println(" paused");
try {
if (sock != null) {
sock.getOutputStream().close();
sock.getInputStream().close();
sock.close();
System.out.println(" everything is closed ");
}
} catch (IOException e) {}
}
}
I know I know, there are some parts of the code that are not used .. my next task is to have this application send commands to the server ... so I'm still experimenting.
when running the application on the emulator it stops before even displaying any of the GUI components. Any idea why ? Here's what the log file says
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.016: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.016: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.126: I/System.out(846): on resume
03-17 08:16:31.447: D/AndroidRuntime(846): Shutting down VM
03-17 08:16:31.447: W/dalvikvm(846): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
03-17 08:16:31.457: E/AndroidRuntime(846): FATAL EXCEPTION: main
03-17 08:16:31.457: E/AndroidRuntime(846): java.lang.RuntimeException: Unable to resume activity {com.example.streamerclient/com.example.streamerclient.MainActivity}: java.lang.NullPointerException
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2742)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2771)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2235)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.os.Looper.loop(Looper.java:137)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.main(ActivityThread.java:5039)
03-17 08:16:31.457: E/AndroidRuntime(846): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 08:16:31.457: E/AndroidRuntime(846): at java.lang.reflect.Method.invoke(Method.java:511)
03-17 08:16:31.457: E/AndroidRuntime(846): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 08:16:31.457: E/AndroidRuntime(846): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 08:16:31.457: E/AndroidRuntime(846): at dalvik.system.NativeStart.main(Native Method)
03-17 08:16:31.457: E/AndroidRuntime(846): Caused by: java.lang.NullPointerException
03-17 08:16:31.457: E/AndroidRuntime(846): at com.example.streamerclient.MainActivity.onResume(MainActivity.java:20)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1185)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.Activity.performResume(Activity.java:5182)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2732)
03-17 08:16:31.457: E/AndroidRuntime(846): ... 12 more
thanks!
Try moving the contents of your entire onResume() to an onCreate() method. Always do the UI setup in onCreate(). Read this: Activity Lifecycle Management.
And take any further queries to stackoverflow :)
Cheers!
You are getting a NullPointerException on line 20 in MainActivity, check that line.
I think this question is better suited for stackoverflow

Categories

Resources