I am currently making an app for android and I have a problem where the UI on a new activity that I start from the main one does not show up. I have no idea what the problem is.
Here is my second activity's layout xml file:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/TableLayout1"
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="com.tabcards.android.Search" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
>
<TableLayout
android:id="#+id/tableScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="yes"
android:padding="5dp"
android:background="#color/gray">
</TableLayout>
</ScrollView>
</TableRow>
Here is my acitiviy's code:
public class Search extends ActionBarActivity {
TableLayout tableScrollView;
String[] JSONExceptions = { "type", "em", "user_id", "id", "profilepic", "bg"};
String value;
JSONObject jObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getString("id");
}
System.out.println(value);
tableScrollView = (TableLayout) findViewById(R.id.tableScrollView);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
jObject = getJson("http://www.tabcards.com/req/androidapi/L2o30H8JlFMtFYHW3KLxkts20ztc5Be6Z6m6v315/json/"
+ value);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
new Thread(new Runnable() {
#Override
public void run() {
try {
createUI(jObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
System.out.println("complete");
}
private void createUI(JSONObject jObject) throws JSONException {
Iterator<?> keys = jObject.keys();
int absIndex = 0;
while( keys.hasNext() ){
String key = (String)keys.next();
if(!contains2(JSONExceptions , jObject.get(key))){
String value = jObject.getString(key);
System.out.println("level 1");
if(value!="") {
insertElement(key + " : " + value, absIndex++);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}
private void insertElement(String data, int i) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newRow = inflater.inflate(R.layout.row, null, false);
newRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView dataTextView = (TextView) newRow
.findViewById(R.id.rowTextView);
dataTextView.setText(data);
System.out.println(dataTextView.getText().toString());
tableScrollView.addView(newRow, i);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
return conn.getInputStream();
}
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public static JSONObject getJson(String url){
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
// HTTP
try {
HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e) {
return null;
}
// Read response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
System.out.println(line);
}
is.close();
result = sb.toString().replace("[", "");
} catch(Exception e) {
return null;
}
// Convert string to object
try {
jsonObject = new JSONObject(result.replace("]", ""));
} catch(JSONException e) {
return null;
}
return jsonObject;
}
This is how I am creating the activity:
Intent i = new Intent(getApplicationContext(), Search.class);
i.putExtra("id",searchEditText.getText().toString());
startActivity(i);
Tell me if you need any more info.
problem:
thread.join();
That problem is dreadlock you are waiting for thread to be done executing, which will put your UI thread to the Blocking state like Thread.Sleep() thus UI thread is waiting for your request to be done executing before it can display the layout in the screen.
from documentation:
Like sleep, join responds to an interrupt by exiting with an InterruptedException.
solution:
Use only one thread which will still wait for the request(createUI) and executes your createUI method after.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
jObject = getJson("http://www.tabcards.com/req/androidapi/L2o30H8JlFMtFYHW3KLxkts20ztc5Be6Z6m6v315/json/"
+ value);
createUI(jObject);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
Related
I have a API link that has a json element named title, and I am trying to store that value into a textview. Here is what I have so far in my main activity code that is supposed to display the contained string:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject jObject;
try {
jObject = new JSONObject("https://chex-triplebyte.herokuapp.com/api/cats?page=0");
String mResponse = jObject.getString("title");
TextView t = (TextView) findViewById(R.id.title_image);
t.setText(mResponse);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The API link I provided works so you can see the value title that I am trying to obtain.
try this:
TextView t = (TextView) findViewById(R.id.title_image);
try {
url = new URL("https://chex-triplebyte.herokuapp.com/api/cats?page=0");
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
//InputStreamReader isw = new InputStreamReader(in);
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String JsonResponse= buffer.toString();
JSONObject jsonobj = new JSONObject(JsonResponse);
JSONArray jarray = jsono.getJSONArray("jsontitle");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
t.setText(object.getString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
but you have to make sure you have a correct json format like this:
{jsontitle:[{"title":"Space Keybaord Cat","timestamp":"2017-09-11T04:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/space.jpg","description":"In space, no one can hear you purr."},{"title":"Jiji","timestamp":"2017-09-11T03:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/jiji.png","description":"You'd think they'd never seen a girl and a cat on a broom before"},{"title":"Limecat","timestamp":"2017-09-11T02:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/lime.jpg","description":"Destroyer of Clockspider and his evil followers, Limecat is the one true god."},{"title":"Astronaut Cat","timestamp":"2017-09-11T01:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/astronaut.jpg","description":"Houston, we have a purroblem"},{"title":"Grumpy Cat","timestamp":"2017-09-11T00:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/grumpy.jpg","description":"Queen of the RBF"},{"title":"Soviet cat","timestamp":"2017-09-10T23:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/soviet.jpg","description":"In soviet Russia cat pets you!"},{"title":"Serious Business Cat","timestamp":"2017-09-10T22:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/serious.jpg","description":"SRSLY GUISE"},{"title":"Sophisticated Cat","timestamp":"2017-09-10T21:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/sophisticated.PNG","description":"I should buy a boat"},{"title":"Shironeko","timestamp":"2017-09-10T20:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/shironeko.png","description":"The zen master kitty"},{"title":"Puss in Boots","timestamp":"2017-09-10T19:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/puss.jpg","description":"Don't you dare do the litter box on me!"}]}
You need to make a network call first parse it to JSONArray first and then get the title from the JSON
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t = (TextView) findViewById(R.id.title_image);
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://chex-triplebyte.herokuapp.com/api/cats?page=0";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray jArray;
try {
jArray = new JSONArray(response);
JSONObject jObject = jArray.getJSONObject(0);
String mResponse = jObject.getString("title");
t.setText(mResponse);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
But this will only show the first title in the response array
If you want to show all titles appended then you can loop over the array
JSONArray jArray;
try {
jArray = new JSONArray(response);
String mResponse = "";
for(int i=0 ;i<jArray.length();i++){
JSONObject jObject = jArray.getJSONObject(i);
mResponse += jObject.getString("title")+" ";
}
t.setText(mResponse);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For using volley you need to include it in dependencies in build.gradle of app
dependencies {
.
.
compile 'com.android.volley:volley:1.0.0'
.
.
}
Try this...
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private String TAG = MainActivity.class.getSimpleName();
private ListView listView;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.item_list);
new GetList().execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
class GetList extends AsyncTask<Void, Void, List<RowItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
}
#Override
protected List<RowItem> doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://chex-triplebyte.herokuapp.com/api/cats?page=0";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray list = new JSONArray(jsonStr);
for (int i = 0; i < list.length(); i++) {
JSONObject c = list.getJSONObject(i);
String title = c.getString("title");
String timestamp = c.getString("timestamp");
String image_url = c.getString("image_url");
String description = c.getString("description");
RowItem item = new RowItem();
item.setTitle(title);
item.setTimestamp(timestamp);
item.setImageUrl(image_url);
item.setDescription(description);
rowItems.add(item);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return rowItems;
}
#Override
protected void onPostExecute(List<RowItem> rowItems) {
super.onPostExecute(rowItems);
if (rowItems != null) {
CustomListViewAdapter adapter = new CustomListViewAdapter(MainActivity.this, R.layout.list_item, rowItems);
listView.setAdapter(adapter);
}
}
}
}
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
private Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.description);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.preview);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDescription());
holder.txtTitle.setText(rowItem.getTitle());
String url = rowItem.getImageUrl();
DownloadImageTask downloadImageTask = new DownloadImageTask(holder.imageView);
downloadImageTask.execute(url);
return convertView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
RowItem.java
public class RowItem {
private String title;
private String timestamp;
private String imageUrl;
private String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/linearLayout2">
<ImageView
android:id="#+id/preview"
android:layout_width="80dp"
android:layout_height="80dp"
app:srcCompat="#mipmap/ic_launcher"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="#string/app_name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/preview"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/app_name"
app:layout_constraintBottom_toBottomOf="#+id/preview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/preview"
app:layout_constraintTop_toBottomOf="#+id/title" />
</android.support.constraint.ConstraintLayout>
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/item_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Note:
item_list.xml has ConstraintLayout implementation.
Result:
I'm new to Android and was working on my first app. I was trying to parse the contents of a Google Sheets spreadsheets, specifically a list of names into a Spinner. I've done so successfully by using an ArrayAdapter with an ArrayList as I can see the options when I expand the Spinner. The problem I'm facing is that the Spinner doesn't show the currently selected item when one is selected. If you try to run my code, you'll see that if you try to click the submit Button, it'll tell you that null is being selected, so I've narrowed down my problem to the currently selected name String not being selected.
Here is my MainActivity class:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
ArrayList<String> names = new ArrayList<String>();
Spinner spBusinessType;
Button btnsubmit;
ArrayAdapter<String> adapterBusinessType;
String sbusinesstype;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spBusinessType = (Spinner) findViewById(R.id.spBussinessType);
btnsubmit=(Button)findViewById(R.id.submit);
btnsubmit.setOnClickListener(this);
new DownloadWebpageTask(new AsyncResult() {
#Override
public void onResult(JSONObject object) {
processJson(object);
}
}).execute("https://spreadsheets.google.com/tq?key=1JKU2Vt_gMNUYYALct4m9xElLdpGlQ3N4uhS9qFRzxOQ");
adapterBusinessType = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);
adapterBusinessType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spBusinessType.setAdapter(adapterBusinessType);
spBusinessType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
sbusinesstype = adapter.getItemAtPosition(position).toString();
System.out.println(sbusinesstype);
// Showing selected spinner item
Toast.makeText(getApplicationContext(),
"Bussiness Type : " + sbusinesstype, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "You have selected " + sbusinesstype,Toast.LENGTH_SHORT).show();
}
private void processJson(JSONObject object) {
try {
JSONArray rows = object.getJSONArray("rows");
for (int r = 0; r < rows.length(); ++r) {
JSONObject row = rows.getJSONObject(r);
JSONArray columns = row.getJSONArray("c");
String name = columns.getJSONObject(0).getString("v");
names.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
the AsyncResult interface I'm using to obtain a JSON object from Google Sheets:
public interface AsyncResult
{
void onResult(JSONObject object);
}
the DownloadWebpageTask class that is obtaining and parsing the JSON object:
public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
AsyncResult callback;
public DownloadWebpageTask(AsyncResult callback) {
this.callback = callback;
}
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to download the requested page.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// remove the unnecessary parts from the response and construct a JSON
int start = result.indexOf("{", result.indexOf("{") + 1);
int end = result.lastIndexOf("}");
String jsonResponse = result.substring(start, end);
try {
JSONObject table = new JSONObject(jsonResponse);
callback.onResult(table);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String downloadUrl(String urlString) throws IOException {
InputStream is = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int responseCode = conn.getResponseCode();
is = conn.getInputStream();
String contentAsString = convertStreamToString(is);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
the activity_main layout file:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<include layout="#layout/content_main" />
</RelativeLayout>
and the content_main layout file that I put the Spinner in:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity">
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Select Business Type"
android:textColor="#000000"
android:textSize="20sp" />
<Spinner
android:id="#+id/spBussinessType"
style="#style/Base.Widget.AppCompat.Spinner.Underlined"
android:layout_width="match_parent"
android:layout_height="wrap_content"></Spinner>
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Submit"
android:textSize="15sp" />
</LinearLayout>
What is causing the adapter to not detect when one of the name strings is being selected? Could it be related to how I'm parsing them from the Google Sheet?
You didnt notify the ArrayAdapter that the data has changed, you originally passed empty Arraylist and upon filling the array list, you have to notifiy the Adapter that data has changed and its time for it to consider that, something like
private void processJson(JSONObject object) {
try {
JSONArray rows = object.getJSONArray("rows");
for (int r = 0; r < rows.length(); ++r) {
JSONObject row = rows.getJSONObject(r);
JSONArray columns = row.getJSONArray("c");
String name = columns.getJSONObject(0).getString("v");
names.add(name);
}
adapterBusinessType.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
That should help.
It would appear no data is being displayed in your Adapter. Nothing can be selected. Your listener code looks fine.
Put adapterBusinessType.notifyDatasetChanged() into the processJson method. Outside the catch or after you add all the data to the list.
Or... replace names.add with adapterBusinessType.add
I have an application and I need to receive images from my database (before someone asks, yes it needs to be from a database).
In my PHP file I send the full complete string, but in Android I only receive half of the string or so.
Do you guys have any tip on why is this happening?
Can anyone help me?
Code
ServerRequest.java:
public void FetchServicoFotoDataInBackground(int CodServico, GetServicoFotoCallBack userCallback) {
new FetchServicoFotoDataAsyncTasck(CodServico, userCallback).execute();
}
public class FetchServicoFotoDataAsyncTasck extends AsyncTask<Void, Void, ArrayList<String>> {
ArrayList<String> ltservico;
int CodServico;
GetServicoFotoCallBack servCallback;
public FetchServicoFotoDataAsyncTasck(int CodServico, GetServicoFotoCallBack servicoCallback) {
this.CodServico = CodServico;
this.servCallback = servicoCallback;
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
ArrayList<String> returnedServico = null;
try {
URL url = new URL(SERVER_ADDRESS + "myphpfile.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("CodServico", this.CodServico+"");
final String postParameters = builder.build().getEncodedQuery();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(postParameters.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoInput(true);
conn.setDoOutput(true);
//send the POST out
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.print(postParameters);
pw.close();
conn.connect();
String result = convertStreamToString(conn.getInputStream());
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
returnedServico = new ArrayList<>();
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
String imagem = json_data.getString("FotoServico");
returnedServico.add(imagem);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", "Erro[" + e.getMessage() + "] ");
}
return returnedServico;
}
#Override
protected void onPostExecute(ArrayList<String> returnedServico) {
servCallback.done(returnedServico);
super.onPostExecute(ltservico);
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
MyActivity.java:
public class verfotoserv extends BaseNavegationActivity {
private LinearLayout lnrVerImages;
private ImageView imageView;
int codservico=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verfotoserv);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
lnrVerImages = (LinearLayout) findViewById(R.id.lnrImages);
final Bundle extras = getIntent().getExtras();
if (extras != null) {
codservico = extras.getInt("CodServico");
}
ServerRequests serverRequests = new ServerRequests(this);
serverRequests.FetchServicoFotoDataInBackground(codservico, new GetServicoFotoCallBack() {
#Override
public void done(ArrayList<String> returnImagens) {
try {
if (returnImagens == null) {
throw new Exception("Não existem dados ou ocorreu um erro no servidor\nTente novamente mais tarde.");
}
for (String imagem : returnImagens) {
Log.i("ImagemRecebida",imagem);
byte[] imageAsBytes = Base64.decode(imagem.getBytes(), Base64.DEFAULT);
imageView = new ImageView(verfotoserv.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(5, 5, 5, 5);
imageView.setLayoutParams(params);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes,0,imageAsBytes.length));
imageView.setAdjustViewBounds(true);
lnrVerImages.addView(imageView);
}
}
catch (Exception erro){
erro.printStackTrace();
showError(erro);
}
}
});
}
private void showError(Exception erro){
Log.e("Erro", erro.getMessage());
AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(verfotoserv.this);
dialogBuilder.setMessage("Erro:"+erro.getMessage());
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
}
MyActivity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroll1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/lnrVerImages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</LinearLayout>
Myphpfile:
<?php
include_once "ligarbd.php";
$codservico = $_POST['CodServico'];
$SQL = "select * from table where CodServico=".$codservico;
$result = mysql_query($SQL);
$imagens = array();
$i = 0;
while ( $postData = mysql_fetch_assoc($result) ) {
$imagens[$i][FotoServico]=base64_encode($postData['FotoServico']);
$i = $i + 1;
}
echo json_encode($imagens);
?>
It was my mistake it was receiving everything just needed to change this
lnrVerImages = (LinearLayout) findViewById(R.id.lnrImages);
To this
lnrVerImages = (LinearLayout) findViewById(R.id.lnrVerImages);
I am getting 20 tweets which takes too much time to load. I want to limit the tweets , but don't know where i should limit the tweets in coding . Is there ayone can tell me to limit the tweets please.
Main Activity
public class MainActivity extends ListActivity {
private ListActivity activity;
final static String ScreenName = "google";
final static String LOG_TAG = "rnc";
ListView listview;
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twit_list);
listview = this.getListView();
activity = this;
downloadTweets();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String lst_txt = parent.getItemAtPosition(position).toString().trim();
// Launching new Activity on selecting single List Item
Intent i = new Intent(MainActivity.this, SingleListItem.class);
// sending data to new activity
i.putExtra("product",lst_txt );
startActivity(i);
}
});
}
// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final static String CONSUMER_KEY = "keyvaluexxxxx";
final static String CONSUMER_SECRET = "secretkeyxxxxxxx";
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
//this.progressDialog = ProgressDialog.show(Boys.this, ""," Look whose back !! Ok Let me see what i have for you ");
try{
progressDialog = new ProgressDialog(MainActivity.this,AlertDialog.THEME_HOLO_DARK);
progressDialog.setIndeterminate(true);
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.loader_2));
progressDialog.setMessage("Please Wait ! Unwrapping Something for You...");
progressDialog.show();
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
}
catch(Exception e)
{
this.progressDialog.dismiss();
Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
#Override
protected void onPostExecute(String result) {
Twitter twits = jsonToTwitter(result);
// lets write the results to the console as well
for (Tweet tweet : twits) {
Log.i(LOG_TAG, tweet.getText());
}
// send the tweets to the adapter for rendering
ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, android.R.layout.simple_list_item_1, twits);
setListAdapter(adapter);
this.progressDialog.dismiss();
}
// converts a string of JSON data into a Twitter object
private Twitter jsonToTwitter(String result) {
Twitter twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitter.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return twits;
}
// convert a JSON authentication object into an Authenticated object
private Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return auth;
}
private String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
private String getTwitterStream(String screenName) {
String results = null;
// Step 1: Encode consumer key and secret
try {
// URL encode the consumer key and secret
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
// Concatenate the encoded consumer key, a colon character, and the
// encoded consumer secret
String combined = urlApiKey + ":" + urlApiSecret;
// Base64 encode the string
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
// Step 2: Obtain a bearer token
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
// Applications should verify that the value associated with the
// token_type key of the returned object is bearer
if (auth != null && auth.token_type.equals("bearer")) {
// Step 3: Authenticate API requests with bearer token
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
// construct a normal HTTPS request and include an Authorization
// header with the value of Bearer <>
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
// update the results with the body of the response
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
}
}
Twitter.java
import java.util.ArrayList;
// a collection of tweets
public class Twitter extends ArrayList<Tweet> {
private static final long serialVersionUID = 1L;
}
TwitterUser.java
public class TwitterUser {
#SerializedName("screen_name")
private String screenName;
#SerializedName("name")
private String name;
#SerializedName("profile_image_url")
private String profileImageUrl;
public String getProfileImageUrl() {
return profileImageUrl;
}
public String getScreenName() {
return screenName;
}
public void setProfileImageUrl(String profileImageUrl) {
this.profileImageUrl = profileImageUrl;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Xml file linked with MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bis"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
where you are doing your get request you can specify count parameter in the api as parameter to get the specific number of counts
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName+"&count=10");
here i am getting 10 manipulate it according to your usage
I am learning to build android applications and I need some help whit getting data from MySQL. I followed this tutorial to do it but I get this error:
Error org.json.JSONEXception: Value of type java.lang.String cannot be converted to JSONObject
On my MainActivity I have one button which when is clicked open second activity. The second activity must get and show data from DB. This is the code of second activity Restaurant.java
public class Restaurants extends Activity {
private String jsonResult;
private String url = "http://10.0.2.2/app1/GetRestaurants.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurants);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> restaurantList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restoranti");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String menu = jsonChildNode.optString("menu");
String outPut = name + "-" + menu;
restaurantList.add(createRestaurants("restoranti", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error " + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, restaurantList,
android.R.layout.simple_list_item_1,
new String[] { "restoranti" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createRestaurants(String name, String menu) {
HashMap<String, String> restaurantNameNo = new HashMap<String, String>();
restaurantNameNo.put(name, menu);
return restaurantNameNo;
}
}
This is the restaurants.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=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp" >
</ListView>
Please let me know if need to post some more code. Many thank's for help.
I also found this answer to the post which is almost similar and tried to make the same but didn't work for me. Same error and blank page.
// Maybe this will help ...
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
// LETS RETURN SOMETING ...
return jsonResult;
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}