Sending String to PHP file via android application - java

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

Related

Whenever Iam not entering anything in EditText the app is crashes [duplicate]

This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 2 years ago.
Iam making a weather app but whenever Iam not entering or entering wrong city name in EditText the app crashes even though I have used try and catch blocks for error handling.The below is the java,xml code and the logs where it is showing a runtime error.
Java
package com.atul.whatstheweather;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText cityName;
TextView weatherInfo;
public class Content extends AsyncTask<String, Void ,String>
{
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
String result = "";
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1)
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherData = jsonObject.getString("weather");
JSONArray array = new JSONArray(weatherData);
for(int i=0;i<array.length();i++)
{
JSONObject jsonPart = array.getJSONObject(i);
String main = jsonPart.getString("main");
String description = jsonPart.getString("description");
weatherInfo.setText("Weather: "+main+"\n\n"+"Description: "+description);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText)findViewById(R.id.cityName);
weatherInfo = (TextView)findViewById(R.id.textView);
}
public void clicked(View view)
{
Content content = new Content();
content.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityName.getText().toString() + "&appid=c20cea76c84b519d67d4e6582064db92");
Log.i("clicked","is working");
}
}
In the Logs given below it is showing Runtime error
Run Logs
05/03 17:35:25: Launching app
Cold swapped changes.
$ adb shell am start -n "com.atul.whatstheweather/com.atul.whatstheweather.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18757 on device xiaomi-redmi_note_3-9b51ac51
I/art: Late-enabling -Xcheck:jni
D/TidaProvider: TidaProvider()
W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
W/ResourceType: No package identifier when getting name for resource number 0x00000000
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
I/InstantRun: Instant Run Runtime started. Android package is com.atul.whatstheweather, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AccessibilityManager: current package=com.atul.whatstheweather, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#9df51ef
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ce6e4fc
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno: QUALCOMM build : a7823f5, I59a6815413
Build Date : 09/23/16
OpenGL ES Shader Compiler Version: XE031.07.00.00
Local Branch : mybranch22028469
Remote Branch : quic/LA.BR.1.3.3_rb2.26
Remote Branch : NONE
Reconstruct Branch : NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
I/clicked: is working
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.atul.whatstheweather, PID: 18757
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:356)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:266)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:60)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
I/Process: Sending signal. PID: 18757 SIG: 9
Application terminated.
App crashes because you are calling Toast in background thread.
Replace your Toast line in catch block Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show(); with :
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
});
Just delete the Toast.makeText

Error: Unused Import Statement - import android.widget.AdapterView.OnItemClickListener; & import android.content.Context;

I have made a simple app which saves and displays bookmarks.
The view bookmarks activity is called by clicking on a menu item in the main activity.
The problem is that when I click the option to view bookmarks stored in view bookmarks Activity, my app crashes.
The problem, I think, is with the bookmark Activity because I have an unused import statement AdapterView.OnItemClickListener & content.Context.
How do I solve this issue?
PS: when I click the option in the main Activity to save a bookmark by launching the save bookmark Activity, it works perfectly.
Here is my code:
BookmarkPage.class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
public class BookmarkPage extends Activity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookmark_page);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllBookmarks();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),DisplayBookmarks.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
bookmark_page.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".BookmarkPage">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Bookmarks"
android:textSize="30sp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView">
</ListView>
</RelativeLayout>
Logcat:
OpenGL ES Shader Compiler Version: E031.25.03.00
Build Date: 12/04/14 Thu
Local Branch:
Remote Branch: quic/LA.BF.1.1_rb1.14
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1_RB1.05.00.00.002.030 + NOTHING
10-03 18:10:35.793 18581-18642/com.carsaleindiaofficial.csitestapp W/cr.media﹕ Requires BLUETOOTH permission
10-03 18:10:35.830 18581-18581/com.carsaleindiaofficial.csitestapp E/libEGL﹕ validate_display:255 error 3008 (EGL_BAD_DISPLAY)
10-03 18:10:35.890 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
10-03 18:10:35.891 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
10-03 18:10:35.922 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
10-03 18:10:35.922 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
10-03 18:10:36.276 18581-18581/com.carsaleindiaofficial.csitestapp W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
10-03 18:10:36.318 18581-18581/com.carsaleindiaofficial.csitestapp W/AwContents﹕ onDetachedFromWindow called when already detached. Ignoring
10-03 18:10:36.836 18581-18681/com.carsaleindiaofficial.csitestapp D/OpenGLRenderer﹕ Render dirty regions requested: true
10-03 18:10:36.902 18581-18581/com.carsaleindiaofficial.csitestapp D/Atlas﹕ Validating map...
10-03 18:10:36.944 18581-18639/com.carsaleindiaofficial.csitestapp W/chromium﹕ [WARNING:data_reduction_proxy_config.cc(630)] SPDY proxy OFF at startup
10-03 18:10:37.192 18581-18681/com.carsaleindiaofficial.csitestapp I/OpenGLRenderer﹕ Initialized EGL, version 1.4
10-03 18:10:37.201 18581-18681/com.carsaleindiaofficial.csitestapp D/OpenGLRenderer﹕ Enabling debug mode 0
10-03 18:10:38.109 18581-18581/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 49 frames! The application may be doing too much work on its main thread.
10-03 18:10:38.213 18581-18581/com.carsaleindiaofficial.csitestapp I/progressBar﹕ Visible
10-03 18:10:38.222 18581-18596/com.carsaleindiaofficial.csitestapp I/art﹕ Background sticky concurrent mark sweep GC freed 10653(792KB) AllocSpace objects, 6(92KB) LOS objects, 12% free, 6MB/7MB, paused 1.507ms total 130.800ms
10-03 18:10:38.894 18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
10-03 18:10:41.925 18581-18596/com.carsaleindiaofficial.csitestapp I/art﹕ Background partial concurrent mark sweep GC freed 12880(607KB) AllocSpace objects, 1(39KB) LOS objects, 40% free, 7MB/11MB, paused 1.053ms total 158.419ms
10-03 18:10:42.812 18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
10-03 18:10:43.549 18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
Problem Starts after progressbar:Gone (i.e when I press the view saved bookmarks option)
10-03 21:13:12.096 18489-18489/com.carsaleindiaofficial.csitestapp I/pageFinished﹕ yesss
10-03 21:13:12.353 18489-18489/com.carsaleindiaofficial.csitestapp I/progressBar﹕ Gone
10-03 21:13:26.413 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 64 frames! The application may be doing too much work on its main thread.
10-03 21:13:28.701 18489-18489/com.carsaleindiaofficial.csitestapp W/art﹕ Before Android 4.1, method int android.support.v7.internal.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
10-03 21:13:30.289 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 129 frames! The application may be doing too much work on its main thread.
10-03 21:13:31.604 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 78 frames! The application may be doing too much work on its main thread.
10-03 21:13:33.328 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 80 frames! The application may be doing too much work on its main thread.
10-03 21:13:35.714 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 38 frames! The application may be doing too much work on its main thread.
10-03 21:13:36.532 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 44 frames! The application may be doing too much work on its main thread.
10-03 21:13:37.719 18489-18489/com.carsaleindiaofficial.csitestapp E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 9 rows, 2 columns.
10-03 21:13:37.777 18489-18489/com.carsaleindiaofficial.csitestapp D/AndroidRuntime﹕ Shutting down VM
10-03 21:13:37.892 18489-18489/com.carsaleindiaofficial.csitestapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.carsaleindiaofficial.csitestapp, PID: 18489
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carsaleindiaofficial.csitestapp/com.carsaleindiaofficial.csitestapp.BookmarkPage}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
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:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at com.carsaleindiaofficial.csitestapp.DBHelper.getAllBookmarks(DBHelper.java:90)
at com.carsaleindiaofficial.csitestapp.BookmarkPage.onCreate(BookmarkPage.java:32)
at android.app.Activity.performCreate(Activity.java:5953)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
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:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
10-03 21:13:43.601 18489-18489/com.carsaleindiaofficial.csitestapp I/Process﹕ Sending signal. PID: 18489 SIG: 9
My database: DBHelper.class
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String BOOKMARKS_TABLE_NAME = "bookmarks";
public static final String BOOKMARKS_COLUMN_ID = "id";
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table bookmarks " +
"(id integer primary key, bmtitle text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS bookmarks");
onCreate(db);
}
public boolean insertBookmark (String title)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("dbtitle", title);
db.insert("bookmarks", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from bookmarks where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, BOOKMARKS_TABLE_NAME);
return numRows;
}
public boolean updateBookmark (Integer id, String title)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", title);
db.update("bookmarks", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteBookmark (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("bookmarks",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllBookmarks()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from bookmarks", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(BOOKMARKS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
MainActivity.class
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends AppCompatActivity {
private WebView view;
ProgressBar progressBar;
ImageView im;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) this.findViewById(R.id.progressBar1);
im = (ImageView) this.findViewById(R.id.imageView2);
String url = "http://www.carsaleindiaofficial.com/?m=1";
view = (WebView) this.findViewById(R.id.webView);
view.setWebViewClient(new MyWebViewClient());
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.loadUrl(url);
}
public class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.i("pageFinished", "yesss");
progressBar.setVisibility(View.GONE);
im.setVisibility(View.GONE);
Log.i("progressBar", "Gone");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
Log.i("progressBar", "Visible");
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("carsaleindiaofficial.com")) {
Log.i("ShldOvrideUrl", "CSI");
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
Log.i("ShldOvrideUrl", "OtherSite");
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.add_bookmark:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Log.i("addBookmark", "loadingAddBookmark");
Intent intent = new Intent(getApplicationContext(),DisplayBookmarks.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
case R.id.show_bookmark:
Log.i("showBookmark", "loadingShowBookmark");
Intent intent2 = new Intent(getApplicationContext(),BookmarkPage.class);
startActivity(intent2);
return true;
case R.id.action_reload:
Log.i("actionReload", "ReloadingURL");
view.loadUrl(view.getUrl());
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (view.canGoBack()) {
view.goBack();
} else {
super.onBackPressed();
}
}
}
Here's your error:
Failed to read row 0, column -1 from a CursorWindow which has 9 rows, 2 columns. ... Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
This is because you create this table:
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table bookmarks " +
"(id integer primary key, dbtitle text)"
);
}
Then you try to access a non existing column:
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(BOOKMARKS_COLUMN_NAME)));
res.moveToNext();
}
Which is defined as a string constant:
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
But it's not created as a table column.
column -1 says that there's no column called bmtitle in your table.
And it's right, because, instead, there is a column named dbtitle.
Quick fix:
Simply change
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
to
public static final String BOOKMARKS_COLUMN_NAME = "dbtitle";

How to list all events on list view with database?

The program/apk need to list all titles , but when i run it apk close please help me i dont know what happens really
package com.eu.agendamarinhagrande;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.eu.agendamarinhagrande.JSONParser;
import com.eu.agendamarinhagrande.R;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> empresaList;
// url to get all products list
private static String url_all_empresas = "http://www.grifin.pt/projectoamg/Conexao.php";
// JSON Node names
private static final String TAG_TITULO = "Titulo";
// products JSONArray
String resultado = null;
ListView lista;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap para el ListView
empresaList = new ArrayList<HashMap<String, String>>();
LoadAllProducts loadAllProducts = new LoadAllProducts();
// Cargar los productos en el Background Thread
lista = (ListView) findViewById(R.id.agenda);
loadAllProducts.execute(String.valueOf(lista));
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}//fin onCreate
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Antes de empezar el background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("A carregar eventos. Por favor espere...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* obteniendo todos los productos
*/
protected String doInBackground(String... args) {
// Building Parameters
List params = new ArrayList();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_empresas, "GET", params);
StringBuilder sb = new StringBuilder();
// Check your log cat for JSON reponse
Log.d("All Products: ", url_all_empresas.toString());
resultado = sb.toString();
try {
// Checking for SUCCESS TAG
// products found
// Getting Array of Products
JSONArray arrayJson = new JSONArray(resultado);
for (int i = 0; i<arrayJson.length();i++){
// Storing each json item in variable
JSONObject c = arrayJson.getJSONObject(i);
String Titulo = c.getString(TAG_TITULO);
// creating new HashMap
HashMap map = new HashMap();
// adding each child node to HashMap key => value
map.put(TAG_TITULO, Titulo);
empresaList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
empresaList,
R.layout.single_post,
new String[]{
TAG_TITULO
},
new int[]{
R.id.single_post_tv_id
});
// updating listview
//setListAdapter(adapter);
lista.setAdapter(adapter);
}
});
}
}
}
Check this line in your onCreate() method:
loadAllProducts.execute(String.valueOf(lista));
you can not get the string value of a ListView! If you want to get the value of a textView IN the listView, you could add an OnItemClick event to your listView and get the value of the textView in the selected list item like this:
//a variable, you could use from all the methods, that will have as a value the value of the selected TextView
private String selectedValue;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
View view = (View)v.getParent();
TextView textYouNeed = (TextView) view.findViewById(R.id.textViewId);
selectedValue = textYouNeed.getText();
}
and then use this variable in the line I told about above:
loadAllProducts.execute(selectedValue);
06-19 11:07:34.233 13804-13804/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
06-19 11:07:34.380 13804-13818/com.eu.agendamarinhagrande I/art﹕ Background sticky concurrent mark sweep GC freed 1879(132KB) AllocSpace objects, 0(0B) LOS objects, 11% free, 538KB/605KB, paused 49.704ms total 65.759ms
06-19 11:07:34.380 13804-13804/com.eu.agendamarinhagrande D/AndroidRuntime﹕ Shutting down VM
06-19 11:07:34.380 13804-13804/com.eu.agendamarinhagrande E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.eu.agendamarinhagrande, PID: 13804
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.eu.agendamarinhagrande/com.eu.agendamarinhagrande.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at com.eu.agendamarinhagrande.MainActivity.onCreate(MainActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Choose activity dynamically during splashscreen

I'm doing a small project, and today I had to make a conditional validation in splashscreen. The project was practically finalized when we decided to do this validation in splashscreen.
Modified my class and was working ok, but I had to include the time for the splash disappears (variable SPLASH_TIME_OUT) and started giving an error that I do not understand.
My splashscreen clas (now) is:
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PesquisaVoto().execute();
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int SPLASH_TIME_OUT = 2000;
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
} else {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
The error I am getting is:
03-03 17:38:49.882 10432-10450/com.clubee.vote D/Create Response﹕ {"voto":[{"count":"1"}],"success":1}
03-03 17:38:49.882 10432-10450/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 17:38:49.892 10432-10450/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 10432
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done
Anyone knows what I did wrong? Is it possivel to implement the Runnable inside the IF statement? If I do not put the timeout variable, everything is right.
UPDATE THE LOG WITH ERROR
03-03 22:01:50.016 18731-18746/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 22:01:50.026 18731-18746/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 18731
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:87)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:48)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
03-03 22:01:50.697 18731-18731/com.clubee.vote E/WindowManager﹕ android.view.WindowLeaked: Activity com.clubee.vote.Splashscreen has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{44aa2458 V.E..... R......D 0,0-681,345} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:350)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:294)
at com.clubee.vote.Splashscreen$PesquisaVoto.onPreExecute(Splashscreen.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.clubee.vote.Splashscreen.onCreate(Splashscreen.java:44)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
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:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
at dalvik.system.NativeStart.main(Native Method)
03-03 22:01:52.529 18731-18746/com.clubee.vote I/Process﹕ Sending signal. PID: 18731 SIG: 9
Tks in advance for answers and comments. I corrected my code, re-wrote and re-structured it, became easier to see where the mistakes were.
below, I leave the code that is working for future research. thank you very much
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static int SPLASH_TIME_OUT = 2000;
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new PesquisaVoto().execute();
}
}, SPLASH_TIME_OUT);
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
}
else {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
I cannot clearly see what is wrong based on the Logs you provided but there is something wrong with your structure.
You are starting an Activity within doInBackground Process and then dismissing the Progress Dialog which belongs to the Activity that you just finished.
Try to pass a parameter to the onPostExecute and then finish your Activity there.
And post some more details from your Log to make it clear. There has to be some more logs indicating what went wrong.

Pass edittext value from android to web services

I want to pass edit text value from android to web services, but i can not do that every time it returns a null value.
This is my simple web services.
package org.me.mongodb;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.ejb.Stateless;
#WebService(serviceName = "Simple")
#Stateless()
public class Simple {
public String testMyProps(#WebParam(name = "name")String fname){
return "First Name : "+fname;
}
}
and android code;
package com.prgguru.android;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import com.example.webserviceactivity.R;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "";
private static final String METHOD_NAME = "testMyProps";
private static final String NAMESPACE = "http://mongodb.me.org/";
private static final String URL = "http://10.0.2.2:8080/Simple/Simple?WSDL";
private String TAG = "PGGURU";
private static String barge="";
private static String info;
Button b;
TextView tv;
EditText et;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.tv_result);
//Button to trigger web service invocation
b = (Button) findViewById(R.id.button1);
//Button Click Listener
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Check if barge text control is not empty
if (et.getText().length() != 0 && et.getText().toString() != "") {
//Get the text control value
barge = et.getText().toString();
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute
task.execute();
//If text control is empty
} else {
tv.setText("Please enter Barge Name");
}
}
});
}
public void testMyProps(String fname) {
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Property which holds input parameters
PropertyInfo getinfo = new PropertyInfo();
//Set Name
getinfo.setName("arg0");
//Set Value
getinfo.setValue(fname);
//Set dataType
getinfo.setType(String.class);
//Add the property to request object
request.addProperty(getinfo);
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
//Set output SOAP object
envelope.setOutputSoapObject(request);
//Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//Invole web service
androidHttpTransport.call(SOAP_ACTION, envelope);
//Get the response
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
//Assign it to info static variable
info = response.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
Log.i(TAG, "doInBackground");
testMyProps(barge);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
tv.setText(info);
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
tv.setText("Getting...");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
}
It returns First name null;
Please help i think i cannot pass the value to web services.
Thanks a lot.
Iam getting this error,
12-11 09:45:53.291: E/AndroidRuntime(1920): FATAL EXCEPTION: main
12-11 09:45:53.291: E/AndroidRuntime(1920): java.lang.IllegalStateException: Cannot execute task: the task is already running.
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.AsyncTask.execute(AsyncTask.java:534)
12-11 09:45:53.291: E/AndroidRuntime(1920): at com.prgguru.android.MainActivity$1.onClick(MainActivity.java:57)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.view.View.performClick(View.java:4240)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.view.View$PerformClick.run(View.java:17721)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.Handler.handleCallback(Handler.java:730)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.Handler.dispatchMessage(Handler.java:92)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.Looper.loop(Looper.java:137)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-11 09:45:53.291: E/AndroidRuntime(1920): at java.lang.reflect.Method.invokeNative(Native Method)
12-11 09:45:53.291: E/AndroidRuntime(1920): at java.lang.reflect.Method.invoke(Method.java:525)
12-11 09:45:53.291: E/AndroidRuntime(1920): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-11 09:45:53.291: E/AndroidRuntime(1920): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-11 09:45:53.291: E/AndroidRuntime(1920): at dalvik.system.NativeStart.main(Native Method)
12-11 09:45:55.031: I/Process(1920): Sending signal. PID: 1920 SIG: 9
You are setting barge with the EditText value but you are not sending it inside AsyncTask
barge = et.getText().toString();
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
if(barge != null && !barge.equals("")) { // if barge is not an empty string and not null
task.execute(barge);
// return null; i don't think u need this return statement
}
And then in your AsyncTask Class
#Override
protected Void doInBackground(String... params) {
Log.i(TAG, "doInBackground: barge is " + params[0]);
testMyProps(params[0]);
}
I think when you instantiate AsyncCallWS, you will have to send the barge in as params.

Categories

Resources