Trying to access database in tab widget - java

I'm sure I have just structured my code wrong or something but I have been looking at it soo long I can see it.
I have managed to get a class working to access my database and bring back data, but when I try to build this class into my tab widget it doesn't seem to work.
This is were I call the class:
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, recipelist.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("recipe").setIndicator("recipe", res.getDrawable(R.drawable.ic_tab_list)).setContent(intent);
tabHost.addTab(spec);
and this is the class with the database code:
package fridge.mate;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class recipelist extends Activity {
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText("gfgfgf...");
}
public static final String KEY_121 = "http://www.bankruptcy.co.uk/1.php"; //i use my real ip here
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","beans"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", name: "+json_data.getString("name")+
", servings: "+json_data.getString("servings")+
", discription: "+json_data.getString("discription")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
txt.setText("Connecting...");
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}

Few notes:
You are calling setContentView() twice. One is enough. So which one is the right one?
You are calling new LinearLayout(getApplicationContext()). Activity is a Context, so you can call new LinearLayout(this). Same for TextView.
I don't see any Tabs. Where are they? I only see LinearLayout and TextView inside it.
You should not perform long-running task in UI thread (EDT). Use AsyncTask for this.
Take a look at Tabs example to see how they did it.

Related

New to okhttp3, no idea why it won't show the results on TextView

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.OkHttpClient;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final TextView textView = findViewById(R.id.text_view_id);
final String IMAGE1 = "storage/emulated/0/Download/image_1.jpeg";
File file1 = new File(IMAGE1);
try {
final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("images", "image_1.jpeg",
RequestBody.create(file1, MEDIA_TYPE_JPEG))
.addFormDataPart("organs", "flower")
.build();
Request request = new Request.Builder()
.url("https://my-api.plantnet.org/v2/identify/all?api-key=123")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
textView.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I understand that I'm trying to run a network activity here on the main thread. That's why I included the StrictMode permitAll thing to get around the issue (I saw an answer to a similar topic that suggested doing so). I am trying to use the PlantNet API here and I use my phone for testing. The same phone where the image is saved.
go see retrofit
it provides a nice and easy way to make your network calls off the main thread

Get XML file from url to Android Application

I have a problem to get .xml data from website and parse to android application, i have try many suggestion but never work. It works fine when i open file in assets folder, but when i try to get from url, it show nothing
This is my Activity Class
package com.android.baliweather;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
public class Prakiraan extends Activity {
/** Called when the activity is first created. */
private ListView listView;
private TextView judul;
private String URL_MAIN = "http://localhost/android/propinsi_17_1.xml";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prakiraan_cuaca);
judul = (TextView) findViewById(R.id.menu1);
listView = (ListView) findViewById(R.id.listview);
bindDataToListing();
}
private void bindDataToListing() {
try {
URL url = new URL("http://localhost/android/propinsi_17_1.xml");
URLConnection connection = url.openConnection();
//URLConnection connection = url.openConnection();
//HttpURLConnection httpConnection = (HttpURLConnection)connection;
//InputStream in = httpConnection.getInputStream();
SAXParserFactory saxparser = SAXParserFactory.newInstance();
SAXParser parser = saxparser.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
XMLParser pc = new XMLParser();
xmlReader.setContentHandler(pc);
//InputStream is = getAssets().open("propinsi_17_1.xml");
//InputStream is = new URL(URL_MAIN).openStream();
xmlReader.parse(new InputSource(connection.getInputStream()));
BindingData bindingData = new BindingData(this, pc.kota, pc.cuaca, pc.suhuMin, pc.suhuMax, pc.kelembapanMin, pc.kelembapanMax, pc.kecepatanAngin, pc.arahAngin);
listView.setAdapter(bindingData);
}
catch (Exception e) {
e.getMessage();
}
}
}
I think the problem only on this class, but i have no idea which one. Please help
It might be android.os.NetworkOnMainThreadException - you're trying to do time-heavy task in a UI thread and the system is preventing you from doing it (you can possibly see this in your logcat). You can implement AsyncTask in order to do it in the background thread.
It may also be that you forgot to add the permission in a manifest file - <uses-permission android:name="android.permission.INTERNET" />

Line -> JSONArray jArray=new JSONArray(result); giving nullpointer exception

package com.example.fyptrialapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
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.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class SearchByName extends Activity{
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream=null;
Intent i;
//public static final String recipes[]=new String[]{"Almond-Sheera","Bhel","Bread-Pizzas","Carrot-Pickle","Carrot-Relish"};
String recipes[];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_recipe);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button b2=(Button)findViewById(R.id.bSearchByName);
try{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2/fypTrial2/searchByName.php");
response = httpclient.execute(httppost); // Execute HTTP Post Request
inputStream = response.getEntity().getContent();
String result=null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line=null;
while((line=reader.readLine())!= null){
sb.append(line+"\n");
}
inputStream.close();
result=sb.toString();
JSONArray jArray=new JSONArray(result);// this statment gives error
for(int i=0;i<jArray.length();i++){
JSONObject json=jArray.getJSONObject(i);
recipes[i]=json.getString("name");
}
}
catch(Exception e){
Log.e("log_tag3", "Error convering result"+e.toString());
}
ArrayAdapter<String> ac=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,recipes);
AutoCompleteTextView tv=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView2);
tv.setAdapter(ac);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent("com.example.practice.Search_Result");
startActivity(i);
}
});
}
}
ERROR
java.nullpointerexception. Error converting result variable.And the
fatal main error
If i want to use ASnk task how should i write it.
JSON syntax never starts as an array. It could be that it starts with { followed by [, but never straight to [. This is why trying to convert your results to JSONArray will not work. You should therefor try to get the object first, then the array elements.
JSONObject jo = new JSONObject(result);
JSONArray jArray = jo.getJSONArray("keyIdentifyer");
If you dont have the array key identifyer, you could try to iterate or get the first element. See this post answear on iterations when no keys are present.
You should indeed use AsyncTask for the networking part. Your app probably already crashes with a NetworkOnMainThread error follow this link for the usasge of AsyncTask.
But that besides, you are providing to little code to point to a reason for the NullPointerException. You should always check if an object is not null if it may occur it is.
try{
//your code
}catch(NullPointerException ex){
ex.printStackTrace();
}

Android connecting to mysql through php

I'm new to android and i would like to create an application that reads data from mysql server. I've taken from web an example about this, but i cannot make it work
I'm using eclipse for this and for the other part, php and mysql.
First of all, here is my php script that is running ok (city.php):
<?php
//connecting to database
$sql=mysql_query("select * from city");
$output = array();
while(list($id,$name)=mysql_fetch_array($sql)){
$output[$id]=$name;
}
print(json_encode($output));
mysql_free_result($sql);
?>
This is returning:
{"1":"Brasov","2":"Bucuresti"}
On my android project from eclipse, I have in the MainActivity.java:
package com.example.mycity;
import android.os.Bundle;
import android.app.Activity;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ParseException;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//e.printStackTrace();
Log.e("log_tag", "Error in http connection: "+e.toString());
}
}
}
But when I'm running this, I receive an error on logcat:it's not connecting to the file:Error in http connection: android.os.NetworkOnMainThreadException
10-24 13:04:34.429: I/dalvikvm(982): threadid=3: reacting to signal 3
10-24 13:04:34.649: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt'
10-24 13:04:34.859: E/log_tag(982): Error in http connection: android.os.NetworkOnMainThreadException
10-24 13:04:34.919: I/dalvikvm(982): threadid=3: reacting to signal 3
10-24 13:04:34.949: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt'
10-24 13:04:35.151: D/gralloc_goldfish(982): Emulator without GPU emulation detected.
10-24 13:04:35.479: I/dalvikvm(982): threadid=3: reacting to signal 3
10-24 13:04:35.499: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt'
I have permission for internet in the AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mycity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I don't know where is the problem. Can anybody help me with this? Thank you!
You may use an AsyncTask class to carry out your network operations as strictmode does not allow it to be done on the main UI example as follows
public class MainActivity extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new httpRequest().execute();
}
private class httprRequest extends AsyncTask<String, Integer, String>{
#override
public String doInBackground(String.... params){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//e.printStackTrace();
Log.e("log_tag", "Error in http connection: "+e.toString());
}
}
}
}
}
The problem is this:
10-24 13:04:34.859: E/log_tag(982): Error in http connection:
android.os.NetworkOnMainThreadException
You need to do your network access on a different thread.
Thank you kabuto178, I'm made the changes and it's connecting. I've wrote the code also for retrieving data from mysql, so who need this, can use my example
Here is the code:
package com.example.mycity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ParseException;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
String result = "";
InputStream is = null;
StringBuilder sb=null;
//String ct_name = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new httprRequest().execute();
int ct_id=0;
String ct_name="";
//Toast.makeText(getBaseContext(), "This is "+result, 3000).show();
try {
Thread.sleep(1000L);
} catch (Exception te) {}
try{
//ct_name = result;
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data= jArray.getJSONObject(i);
ct_id=json_data.getInt("CITY_ID");
ct_name += json_data.getString("CITY_NAME")+":";
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
TextView tv1 = (TextView) findViewById(R.id.textView1);
tv1.setText(ct_name);
}
private class httprRequest extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//e.printStackTrace();
Log.e("log_tag", "Error in http connection: "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
//Toast.makeText(getBaseContext(), "Am eroare aici", 3000).show();
Log.e("log_tag", "Error converting result "+e.toString());
}
/*
Toast.makeText(getBaseContext(), "Here i am", 3000).show();
*/
return result;
}
}
}
I have to change a little bit the code, cause i put a thread.sleep. Instead of it, i have to check if i have a value into result (in a while loop). I think this is happening because at that moment when i try to parse the value, i don;t have a value in result.
The php code is:
<?php
//connecting to database
$sql=mysql_query("select * from city where CITY_NAME like '%'");
$output = array();
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
echo json_encode($output);
mysql_free_result($sql);
?>
Table 'city' has two columns, CITY_ID and CITY_NAME.

How to use eclipse debug in android

I am attempting to use java FileInputStream to write some strings to a text file that will be stored on the android internal storage. However my virtual device keeps throwing an exception and I am not sure what or where I should be looking as the DDMS log cat function does not give me any useful information. I am using a try/catch structure with a stack trace print as shown below. I am not very familiar with the debug function in relation to android and I am not sure where else I can look to find out what is going on. Code is below.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText textBox;
private static final int READ_BLOCK_SIZE = 100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textBox = (EditText)findViewById(R.id.textView1);
Button saveBtn = (Button)findViewById(R.id.button1);
Button loadBtn = (Button)findViewById(R.id.button2);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = textBox.getText().toString();
try{
FileOutputStream fOut =
openFileOutput("textfile.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//---write the string to the file---
osw.write(str);
osw.flush();
osw.close();
//---display file saved message---
Toast.makeText(getBaseContext(), "File saved successfully!!", Toast.LENGTH_SHORT).show();
//---clears the EditText---
textBox.setText("");
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
loadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
FileInputStream fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[]inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while((charRead = isr.read(inputBuffer))>0){
//---convert the char to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
//---set the EditText to the text that has been read---
textBox.setText(s);
Toast.makeText(getBaseContext(), "File loaded successfully!!", Toast.LENGTH_SHORT).show();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
}
}
did you set your permissions in your manifest for writing?
and is your device a droidx (which when you plug in the USB cable, unmounts the external storage, making it inaccessible).
Why not run the debugger and put in debug points and see how far it gets before it crashes?

Categories