It doesn't show the text from internet, just shows 000.
I wanted to get a text from internet and show on widget.
But I haven't got it to work successfully.
This is the code (Java class):
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.RemoteViews;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class simple_widget extends AppWidgetProvider {
public void onCreateView(Context context, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.activity_simple_widget);
remoteViews.setTextViewText(R.id.textView, str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
}
What's wrong with the code?
You need to modify it using RemoteViews. You can't actually modify a view on the appwidget directly
Here are a few examples
I take it you want to use setText() in appWidgetProvider class. But this class does not allow findViewById(). You need to use a function of RemoteView Class for this purpose.
CharSequence Method | Android Developers
in your case:
remoteViews.setCharSequence(R.id.textView,"setText",str);
it works for EditText,TextView,TextClock.
You can replace String MethodName with the name of method like getText,setText,setTimeZone etc.
For Buttons RemoteViews offer the following function
setOnClickResponse | Android Developers
this is the equivalent of
View.setOnClickListener(android.view.View.OnClickListener)
Similarly a lot of other methods are available now such as setFloat(), setLong() which work same as setCharSequence().
you can choose between them based on the datatype of parameters you want to pass.
here is the link to understand and view the list of all RemoteView functions
RemoteViews | Android Developers
Hope this helps
Related
I've seen this question, it's not my case, since I don't have backslashes in my url,
I have simple URL like, https://url.com/login
My Code,
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class LoginActivity extends AppCompatActivity {
URL url = new URL("https://url.net/login/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.submitbtn);
EditText edtxt = (EditText) findViewById(R.id.usernm);
EditText edtxt2 = (EditText) findViewById(R.id.usrpwd);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(i);
}
});
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
}
}
Screen shot:
When I hover on new URL();, I get error as:
Unhandled Exception: java.net.MalformedURLException
That's why I'm getting another error at line,
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
in stack Trace I'm getting error as,
Error:(48, 13) error: cannot find symbol method readStream(InputStream)
When I hover on new URL();, I get error as:
The URL() constructor throws java.net.MalformedURLException. You need to wrap that constructor call in a try/catch block.
That's why I'm getting another error at line,
That is because getInputStream() also throws checked exceptions. You need to wrap that code in a try/catch block.
That's the line of error and I'm getting error as Error:(48, 13) error: cannot find symbol method readStream(InputStream)
That is because you did not implement a method named readStream() on this class.
All of this is covered in any decent book or course on Java programming.
Eventually, once you get past these compile errors, your code will crash at runtime with a NetworkOnMainThreadException, as you cannot perform network I/O on the main application thread. You will need to move this HTTP code to a background thread, either one that you create yourself or by using an HTTP client API that can handle it for you (e.g., OkHttp).
I'm currently developing an Android application for a university stage.
This application has to draw a plot with data which are coming from some pressure sensor, to draw this plot I'm using Androidplot library.
I'm following this example on Andrloidplot docs to create a dynamic XYPlot and I have imported androidplot-core:1.1.0 in the project dependencies.
In the code editor I'm getting the "Cannot resolve .... method" error everytime I call getGraphWidget(), setRangeValueFormat() and when I try to access XYStepMode fields.
I have searched for this issue on internet and on Androidplot docs but I haven't find anything usefull.
I think that this is produced by some import that I have missed, but I'm not figuring out what I've forgotten.
Someone has already dealed with this problem and solved it?
Here's a part of my class where I get the first error occurrence, it is on the last line:
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.androidplot.Plot;
import com.androidplot.util.PixelUtils;
import com.androidplot.xy.XYSeries;
import com.androidplot.xy.*;
import java.text.DecimalFormat;
import java.util.Observable;
import java.util.Observer;
/**
* Created by marco on 07/09/16.
*/
public class GraphicChart extends Fragment {
private XYPlot dynamicPlot;
private MyPlotUpdater plotUpdater;
SampleDynamicXYDatasource data;
private Thread myThread;
public GraphicChart(){}
// redraws a plot whenever an update is received:
private class MyPlotUpdater implements Observer {
Plot plot;
public MyPlotUpdater(Plot plot) {
this.plot = plot;
}
#Override
public void update(Observable o, Object arg) {
plot.redraw();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.graphic_chart_fragment, container, false);
// get handles to our View defined in layout.xml:
dynamicPlot = (XYPlot)getActivity().findViewById(R.id.dynamic_plot);
plotUpdater = new MyPlotUpdater(dynamicPlot);
// only display whole numbers in domain labels
dynamicPlot.getGraphWidget().setDomainValueFormat(new DecimalFormat("0")); //FIRST ERROR ON THIS LINE
Finally I've resolved it, I've compared sources from the site I've linked and the one on gitHub.
Here changes I've made:
lines
// only display whole numbers in domain labels
dynamicPlot.getGraphWidget().setDomainValueFormat(new DecimalFormat("0"));
are now
// only display whole numbers in domain labels
dynamicPlot.getGraph().getLineLabelStyle(XYGraphWidget.Edge.BOTTOM).
setFormat(new DecimalFormat("0"));
XYStepMode is now only StepMode
The call to dynamicPlot.setRangeValueFormat(new DecimalFormat("###.#")); is now done in this way
dynamicPlot.getGraph().getLineLabelStyle( XYGraphWidget.Edge.LEFT).setFormat(new DecimalFormat("###.#"));
I'm trying to build an plugin-system which is importing Fragments from other apks as described here.
Eclipse keeps telling me:
12-01 15:17:18.609: W/dalvikvm(23425): Class resolved by unexpected DEX: Lde/anthropotec/activityapp/firstplugin/UI;(0x42901520):0x57d93000 ref [Lde/anthropotec/activityapp/api/PluginAPI;] Lde/anthropotec/activityapp/api/PluginAPI;(0x428eb2b8):0x527e1000
(Lde/anthropotec/activityapp/firstplugin/UI; had used a different Lde/anthropotec/activityapp/api/PluginAPI; during pre-verification)
Which isn't a suprise, as I'm importing my PluginAPI-libary in both, the Host and the Plugin. As far as I understand, Eclipse seems to be afraid, that these libaries aren't identical. Is there a way to tell Eclipse to not import the libary, if it's already there in the other apk? Or is there any other way to go around this. Please tell me if you need more information. Here's my source:
The Host:
package de.anthropotec.activityapp.host;
import java.io.File;
import dalvik.system.DexClassLoader;
import de.anthropotec.activityapp.api.PluginAPI;
import de.anthropotec.activtiyapp.host.R;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
public class MainActivtiy extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Class<?> requiredClass = null;
final ApplicationInfo info = getPackageManager().getApplicationInfo("de.anthropotec.activityapp.firstplugin",0);
final String apkPath = info.sourceDir;
final File dexTemp = getDir("temp_folder", 0);
final String fullName = "de.anthropotec.activityapp.firstplugin.UI";
boolean isLoaded = true;
// Check if class loaded
try {
requiredClass = Class.forName(fullName);
} catch(ClassNotFoundException e) {
isLoaded = false;
}
if (!isLoaded) {
final DexClassLoader classLoader = new DexClassLoader(apkPath, dexTemp.getAbsolutePath(), null, getApplicationContext().getClassLoader());
requiredClass = classLoader.loadClass(fullName);
}
if (null != requiredClass) {
// Try to cast to required interface to ensure that it's can be cast
final PluginAPI holder = PluginAPI.class.cast(requiredClass.newInstance());
if (null != holder) {
final Fragment fragment = holder.getFragment();
if (null != fragment) {
final FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.add(R.id.pluginPlace, fragment, "MyFragment").commit();
}
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
The PluginApi:
package de.anthropotec.activityapp.api;
import android.app.Fragment;
public interface PluginAPI {
public Fragment getFragment();
}
And the Plugin-Fragment itself:
package de.anthropotec.activityapp.firstplugin;
import de.anthropotec.activityapp.api.PluginAPI;
import android.app.Fragment;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class UI extends Fragment implements PluginAPI{
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
// Note that loading of resources is not the same as usual, because it loaded actually from another apk
final XmlResourceParser parser = container.getContext().getPackageManager().getXml("de.anthropotec.testplugin", R.layout.ui, null);
return inflater.inflate(parser, container, false);
}
#Override
public Fragment getFragment() {
return this;
}
}
Each of the above as it's own Project (PluginAPI as libary). The question isn't quite new (e.g. here), but the already given answers advice to remove on of the imports, what doesn't seem to be a option in my case, as I need the API on both sides (Plugin and Host).
Ahww, sometimes it's so obvious. Just import the libary as extern libary in Properties->Java Build Path -> add external jar for the Plugin, and everything works just fine. Gnarf!
I'm using this code to show images from url in list view so im using this class that extended from simpleAdapter
package com.mypackage.lebadagency;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
public class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
// TODO Auto-generated constructor stub
}
#Override
public void setViewImage(ImageView v, String value) {
UrlImageViewHelper.setUrlDrawable(v, value);
}
}
and using it is like :
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new MyAdapter(
EconomyPanel.this, contactList,
R.layout.economy_list_item, new String[] {TAG_ID, TAG_IMAGE_URL,TAG_NAME
}, new int[] {R.id.idTV, R.id.image1,
R.id.name });
setListAdapter(adapter);
}
my list load 10 items, my problem is that it does not load all the 10 images , sometimes it only loads one of them , what is the problem and how to fix it ??
The problem is not with this code , this code is working no need to change the method of viewing the image or anything the problem is simpler than that , any image that contain space gab in its file name , the browsers can handle it by replacing the space with %20 , and when android retrieve the image url it retrieve it without the 20% symbol , so i need to add this command to the url :
value=value.replaceAll(" ", "%20");
and then
UrlImageViewHelper.setUrlDrawable(v, value);
I'm making an app which reads a certain part of a website and posts it to the screen. The app currently works in my android emulator but when I transfer it to my galaxy S2, it doesn't seem to access the website at all.
package com.example.beam;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
String current = null;
Button check;
TextView text;
TextView url;
String[] lines = new String[12];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check = (Button) findViewById(R.id.checkstatus);
text = (TextView) findViewById(R.id.textView1);
url = (TextView) findViewById(R.id.url);
String[] lines = new String[12];
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// Attempt to the read the source from a website.
String bodyHtml = "null";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.spring8.or.jp/ext/ja/status/text.html");
ResponseHandler<String> resHandler = new BasicResponseHandler();
try {
bodyHtml = httpClient.execute(httpGet, resHandler);
} catch (Exception e) {
e.printStackTrace();
}
double current = 0;
try{
String derp = bodyHtml.substring(bodyHtml.lastIndexOf("mA") - 5, bodyHtml.lastIndexOf("mA"));
current = Double.parseDouble(derp);
}
catch(Exception e){
}
url.setText(current + " mA");
}
});
}
}
Apologies if the coding is a bit poor and messy, I'm quite new to all this. How do I fix this issue? Thank you
Also, I'm pretty sure I've set the permission correctly in the manifest.
Try this....
Its a good practice to Keep the UI work on UI thread and Non-UI work on Non-UI thread, but that became a LAW from the release of HONEYCOMB Android version.... That may be causing the error.
So you can do the following....
Do the Http on a separate thread, and then place the value on the UI using Handler, Handler Keep the reference of the thread in which it was created.
You can use AsyncTask which is specially designed for android to make a sync between
UI and Non-UI thread.
Note:
Please check the Internet Permission in AndroidManifest, though i know you have done it, cause the app ran on the emulator.... but still..no harm in checking it again.