I am new to android and am trying to get a json file from an api and seem to be getting errors. I do not know where the error is coming from. I created a new thread and in the run method have the code to get the data from the api. I have the response string being logged but an error keeps coming up instead.
This is the code to my main activity
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.Buffer;
import java.util.*;
public class MainActivity extends AppCompatActivity implements BookListFragment.OnFragmentInteractionListener {
final ArrayList<Book> names = new ArrayList<Book>();
private boolean twoPane = false;
BookListFragment blf;
BookDetailsFragment bdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twoPane = findViewById(R.id.container2) == null;
Context context = getApplicationContext();
Resources res = context.getResources();
final String searchString = "";
Thread t = new Thread(){
#Override
public void run(){
URL bookData;
try{
bookData = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
HttpURLConnection conn = (HttpURLConnection) bookData.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String response = "", tmpResponse;
tmpResponse = br.readLine();
while(tmpResponse != null){
response= response + tmpResponse;
Log.d("response", tmpResponse);
tmpResponse = br.readLine();
}
Log.d("Response", response);
JSONObject bookObject = new JSONObject(response);
Message msg = Message.obtain();
msg.obj = bookObject;
} catch (Exception e){
e.printStackTrace();
}
}
};
/*if(twoPane){
ViewPagerFragment vp = ViewPagerFragment.newInstance(names);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container1,vp);
ft.commit();
} else {
blf = BookListFragment.newInstance(names);
bdf = BookDetailsFragment.newInstance(names.get(0));
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container1, blf);
ft.replace(R.id.container2,bdf);
ft.addToBackStack(null);
ft.commit();
}*/
}
Handler responseHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
JSONObject respObject = (JSONObject) msg.obj;
return false;
}
});
#Override
public void onItemSelection(Book bookname) {
bdf.updateBookName(bookname);
}
}
and this is the error
2019-11-14 16:47:38.682 2848-12759/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.b.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.microdetection.d.k.a(SourceFile:91)
at com.google.android.apps.gsa.staticplugins.microdetection.d.l.run(Unknown Source:14)
at com.google.android.libraries.gsa.runner.a.a.b(SourceFile:32)
at com.google.android.libraries.gsa.runner.a.c.call(Unknown Source:4)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at com.google.android.apps.gsa.shared.util.concurrent.b.g.run(Unknown Source:4)
at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
at com.google.android.apps.gsa.shared.util.concurrent.b.i.run(SourceFile:6)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.j(SourceFile:103)
at com.google.android.apps.gsa.speech.audio.au.read(SourceFile:2)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.ao.run(SourceFile:17)
at com.google.android.apps.gsa.speech.audio.an.run(SourceFile:2)
and this
2019-11-14 16:47:43.735 2848-12762/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.b.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.microdetection.d.k.a(SourceFile:91)
at com.google.android.apps.gsa.staticplugins.microdetection.d.l.run(Unknown Source:14)
at com.google.android.libraries.gsa.runner.a.a.b(SourceFile:32)
at com.google.android.libraries.gsa.runner.a.c.call(Unknown Source:4)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at com.google.android.apps.gsa.shared.util.concurrent.b.g.run(Unknown Source:4)
at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
at com.google.android.apps.gsa.shared.util.concurrent.b.i.run(SourceFile:6)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.j(SourceFile:103)
at com.google.android.apps.gsa.speech.audio.au.read(SourceFile:2)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.ao.run(SourceFile:17)
at com.google.android.apps.gsa.speech.audio.an.run(SourceFile:2)
The correct version of the code should the the data is got and saved into the response string and saves into a JSONObject. The correct output should be for the response string to be logged in the log cat.
good day sir. you open a connection but you did not connect to the url. try typing conn.connect()
Related
I am trying to read a file as inputstream to fill in the file with additional data. This data is then supposed to be sent over to a second activity which unwraps the data and displays it on the screen. this is my code
package com.example.daniel.finalproject;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class Secondactivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
}
public void Proceed(View view) {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
}
}
However this line: InputStream is = am.open("madlibsimple.txt");
returns the error. madlibsimple.txt is in the assetsfolder, but I
don't know what goes wrong. Any help would be much appreciated.
open(String file) can throw an error (i expect IOException) that you have to catch with an
try {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
} catch (Exception e) {
e.printStacktrace();
}
statement.
This whole topic is not about what goes wrong, but what COULD go wrong
For more information on the topic of exceptions and errorhandling you can click here
I have created REST web service using jersey which returns JSON response. JSON response returned by web service is as follow-
{
"Disease": "Bacterial_blight",
"Control": "Foliar sprays of streptocycline sulphate # 0.5 gm/land copper-oxychlode # 3 g / l of water as and when symptoms seen."
}
I have made Android app activity for demo purpose which contains one radio button, one Edit text box and one Button to submit the parameters to REST web service. But Problem is I'm getting force close when I try to click on Submit Button.
This is the actual android activity class code-
package com.doitgeek.agroadvisorysystem;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class DiseaseResultActivity extends AppCompatActivity {
public TextView diseaseTV;
public TextView controlMechanismTV;
public EditText etSymptom;
public RadioButton rbL;
public Button btnSubmit;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disease_result);
diseaseTV = (TextView)findViewById(R.id.diseaseTV);
controlMechanismTV = (TextView)findViewById(R.id.controlMechanismTV);
etSymptom = (EditText)findViewById(R.id.etSymptom);
rbL = (RadioButton)findViewById(R.id.rbL1);
btnSubmit = (Button)findViewById(R.id.btnSubmit);
}
public void onClickSubmit(View view) {
RequestParams params = new RequestParams();
String affectedPart = rbL.getText().toString();
String symptom = etSymptom.getText().toString();
params.put("affectedPart", affectedPart);
params.put("symptom", symptom);
invokeWS(params);
}
/* Invocation of RESTful WS */
public void invokeWS(RequestParams params) {
dialog.show();
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.0.100:8080/AgroAdvisorySystem/webapi/disease_prediction/result", params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
dialog.hide();
try {
JSONObject obj = (JSONObject)new JSONTokener(response.toString()).nextValue();
JSONObject obj2 = obj.getJSONObject("Disease");
String disease = obj2.toString();
/*JSONObject obj = new JSONObject(response);
String disease = obj.getJSONObject("Disease").toString();*/
diseaseTV.setText(disease);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error Occurred [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
dialog.hide();
if(statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if(statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occurred! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}
}
I didn't find working solution till now that is why I am posting this as question.
So, what`s the Exception record?
It seems that the problem is in:
JSONObject obj2 = obj.getJSONObject("Disease");
where the item Disease is no longer a JSONObject.
Try obj.getSyting("Disease")
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hello im new in stackover flow i want to try these website and ask for someones help in my android when i change the intent there's an error in my android monitor in android studio here is it.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kim.checkerv3, PID: 2970
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kim.checkerv3/com.example.kim.checkerv3.BudgetOutput}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at com.example.kim.checkerv3.BudgetOutput.onCreate(BudgetOutput.java:22)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
i didn't understand this i'd tried researching for solution and im still stuck on it.
Here the intent will be pass to other java class.
package com.example.kim.checkerv3;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by KIM-PC on 12/5/2016.
*/
public class BudgetFragment extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_budget, container, false);
final EditText etCash = (EditText) v.findViewById(R.id.etCash);
final Button bBudget = (Button) v.findViewById(R.id.bBudget);
bBudget.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
SharedPreferences sharedpref = getContext().getSharedPreferences("user_id", MODE_PRIVATE);
String id = sharedpref.getString("user_id","");
final int budgeted = Integer.parseInt(etCash.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray arr = jsonResponse.getJSONArray("message");
boolean success = jsonResponse.getBoolean("success");
System.out.println(budgeted/arr.length());
int total = budgeted/arr.length();
if (success) {
Intent intent = new Intent(getContext(), BudgetOutput.class);
Bundle b = new Bundle();
b.putString("total", String.valueOf(total));
getContext().startActivity(intent);
if (arr != null) {
int sum = 0;
for(int i = 0;i<arr.length();i++){
//listdata.add(arr.get(i).toString());
String money = arr.getJSONObject(i).getString("amount");
sum += Integer.parseInt(money);
}
SharedPreferences sharedPref1 = getActivity().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref1.edit();
editor.putInt("TotalSum", sum);
editor.commit();
System.out.println(sum);
//arrayAdapter.notifyDataSetChanged();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Failed to fetch. Try again.")
.setNegativeButton("OK", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RecordRequest recordRequest = new RecordRequest(id, responseListener);
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(recordRequest);
}
});
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
SharedPreferences sharedpref1 = getContext().getSharedPreferences("mypref", MODE_PRIVATE);
int budgeted = sharedpref1.getInt("TotalSum", 0);
System.out.println(budgeted/2);
}
}
and the class where the intent will be get.
package com.example.kim.checkerv3;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by KIM-PC on 12/6/2016.
*/
public class BudgetOutput extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_output);
final TextView tvOutput = (TextView) findViewById(R.id.tvoutput);
Bundle b = getIntent().getExtras();
String output=b.getString("total");
if(b !=null)
output = b.getString("total");
tvOutput.setText(output+" Per cheque record.");
}
}
if there is someone who could solve i appreciate and give my thanks to you.
Well, you forgot to add your Bundle to the Intent
Intent intent = new Intent(getContext(), BudgetOutput.class);
Bundle b = new Bundle();
b.putString("total", String.valueOf(total));
intent.putExtras(b);
getContext().startActivity(intent);
I am trying to push url using Parse.com and i added a code in which get String is showing error. Can anyone help me out please!
Help me out Please! Getting an Error
The method getString(String) is undefined for the type String**
package com.example.pushnotificationdemo;
import org.json.JSONObject;
import com.example.pushnotificationdemo.R;
import com.parse.ParseAnalytics;
import com.parse.ParseInstallation;
import com.parse.PushService;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends ActionBarActivity {
WebView webframe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String jsonData = extras.getString("com.parse.Data");
JSONObject json = new JSONObject(jsonData);
String pushStore = json.getString("data");
if(pushStore!=null) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pushStore.getString("url")));
startActivity(browserIntent);
}
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
/** Cerco l'elemento in /res/layout/main.xml */
webframe = (WebView) findViewById(R.id.webview);
/** Javascript abilitato (ma non flash) */
webframe.getSettings().setJavaScriptEnabled(true);
/** Simulo il webbrowser chrome di android*/
webframe.setWebChromeClient(new WebChromeClient());
webframe.setWebViewClient(new WebViewClient());
/** Assegno l'url di apertura del webframe */
webframe.loadUrl("http://www.dlybugs.com");
}
}
You're getting the error from this code:
pushStore.getString("url")
because pushStore is a String. It's not a JSONObject that you can call getString on. You probably want this code instead:
String pushStore = json.getString("data.url");
if(pushStore!=null) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pushStore));
startActivity(browserIntent);
}
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
Hi i want to fetch the selected column from mysql by matching one column name i.e
"select column_name from day where date='$date'"
But it is giving me serious error , i have check the connectivity issues they are fine , i think there is some problem in code please help me
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
public class Day extends Activity {
String dt="";
String mc="";
String bc="";
ImageView dateimg;
String name;
String date;
InputStream is=null;
String result=null;
String line=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.day_lay);
getCurrDate();
select();
dateimg = (ImageView) findViewById(R.id.img);
dateimg.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//getCurrDate();
}
});
}
public String getCurrDate()
{
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
mc = dt.substring(0, dt.length() - 17);
bc=mc.substring(4);
System.out.println("Date is"+bc);
date=bc;
return dt;
}
public void select()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("date",date));
try
{
HttpClient httpclient = new DefaultHttpClient()
HttpPost httppost = new HttpPost("http://192.168.1.1/wpcontent/themes/app/day.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
System.out.println("Got Value"+name);
}
}
// Database select
<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db="android";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$date=$_REQUEST['date'];
$r=mysql_query("select mat from vicks where date='$date'",$con);
while($row=mysql_fetch_array($r))
{
$flag[name]=$row[name];
}
print(json_encode($flag));
mysql_close($con);
?>
//Logcat
05-08 14:04:34.938: I/dalvikvm-heap(995): Grow heap (frag case) to 54.839MB for 2312016-byte allocation
05-08 14:04:35.218: D/dalvikvm(995): GC_CONCURRENT freed 1K, 4% free 56085K/58055K, paused 11ms+23ms
05-08 14:04:35.758: D/dalvikvm(995): GC_FOR_ALLOC freed 564K, 4% free 56086K/58055K, paused 172ms
05-08 14:04:35.788: I/dalvikvm-heap(995): Grow heap (frag case) to 57.044MB for 2312016-byte allocation
05-08 14:04:36.538: D/dalvikvm(995): GC_CONCURRENT freed <1K, 4% free 58344K/60359K, paused 11ms+98ms
05-08 14:08:30.258: I/System.out(995): Date is8
05-08 14:08:30.298: E/Fail 1(995): android.os.NetworkOnMainThreadException
05-08 14:08:30.338: E/Fail 2(995): java.lang.NullPointerException
05-08 14:08:30.338: E/Fail 3(995): java.lang.NullPointerException
05-08 14:08:30.338: I/System.out(995): Got valuenull
This is not about connectivity. This is about handling network activity on the main thread.
You can either disable that warning (which is bad practice) or perform that task in a separate thread.
A common Android pattern is using an AsyncTask for that.
The AsyncTask class uses three paramters in its constructor: params, progress, result. In your case they can all be null if you only need to run something in the background.
private class DatabaseTask extends AsyncTask<void, void, void>
{
protected void doInBackground(Void... params)
{
// YOUR DB CODE
}
}
And execute like this:
new DatabaseTask().execute();
Or, you can change the first void to whatever type you need if you want to use input parameters. Read more here.